text stringlengths 13 6.01M |
|---|
namespace Sentry.Internal.ScopeStack;
internal class AsyncLocalScopeStackContainer : IScopeStackContainer
{
private readonly AsyncLocal<KeyValuePair<Scope, ISentryClient>[]?> _asyncLocalScope = new();
public KeyValuePair<Scope, ISentryClient>[]? Stack
{
get => _asyncLocalScope.Value;
set => _asyncLocalScope.Value = value;
}
}
|
#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
#endregion
namespace Sideris
{
public partial class TransfersView : UserControl
{
public TransfersView(FilesDataSet files)
{
InitializeComponent();
downloader.Files = files;
UpdateView();
}
public void UpdateView()
{
if(listView.InvokeRequired)
{
listView.Invoke(new MethodInvoker(this.UpdateView));
return;
}
listView.Items.Clear();
foreach(Downloader.Download download in downloader.Downloads)
{
ListViewItem item = listView.Items.Add(download.FullName);
item.Tag = download;
item.ImageIndex = download.IsRunning ? 0 : 1;
item.SubItems.Add(download.Size.ToString());
item.SubItems.Add(download.Completed.ToString());
item.SubItems.Add(String.Format("{0}%",
(int) (download.Completed * 100 / download.Size)));
}
}
private delegate void UpdateViewInvoker(Downloader.DownloadEventArgs e);
private void UpdateView(Downloader.DownloadEventArgs e)
{
if(listView.InvokeRequired)
{
listView.Invoke(new UpdateViewInvoker(this.UpdateView), e);
return;
}
foreach(ListViewItem item in listView.Items)
{
if(item.Tag == e.Download)
{
item.SubItems[2].Text = e.Download.Completed.ToString();
item.SubItems[3].Text = String.Format("{0}%",
(int) (e.Download.Completed * 100 / e.Download.Size));
}
}
}
public void AddDownload(string fullPath, string hash, long size, List<string> hosts)
{
downloader.AddDownload(fullPath, hash, size, hosts);
UpdateView();
}
private void downloader_DownloadProgressChanged(object sender, Downloader.DownloadEventArgs e)
{
UpdateView(e);
}
private void startToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach(ListViewItem item in listView.SelectedItems)
{
Downloader.Download download = item.Tag as Downloader.Download;
if(!download.IsRunning)
{
download.Start();
}
}
UpdateView();
}
private void pauseToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach(ListViewItem item in listView.SelectedItems)
{
Downloader.Download download = item.Tag as Downloader.Download;
if(download.IsRunning)
{
download.Stop();
}
}
UpdateView();
}
private void downloader_DownloadCompleted(object sender, Downloader.DownloadEventArgs e)
{
UpdateView();
}
private void contextMenuStrip_Opened(object sender, EventArgs e)
{
bool canStart = false;
bool canPause = false;
bool canCancel = false;
if(listView.SelectedItems.Count > 0)
{
canCancel = true;
}
foreach(ListViewItem item in listView.SelectedItems)
{
Downloader.Download download = item.Tag as Downloader.Download;
if(download.IsRunning)
{
canPause = true;
}
else
{
canStart = true;
}
}
startToolStripMenuItem.Enabled = canStart;
pauseToolStripMenuItem.Enabled = canPause;
cancelToolStripMenuItem.Enabled = canCancel;
}
private void cancelToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach(ListViewItem item in listView.SelectedItems)
{
Downloader.Download download = item.Tag as Downloader.Download;
download.Cancel();
}
UpdateView();
}
}
}
|
using CaveGeneration.Models;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Linq;
using System;
using CaveGeneration.Content_Generation.Goal_Placement;
using CaveGeneration.Content_Generation.Astar;
using System.Collections.Generic;
using CaveGeneration.Models.Characters;
using CaveGeneration.Content_Generation.Enemy_Placement;
using CaveGeneration.Content_Generation.Parameter_Settings;
using Microsoft.Xna.Framework.Media;
using CaveGeneration.Content_Generation.Pitfall_Placement;
namespace CaveGeneration
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Camera camera;
FrameCounter frameCounter;
Texture2D block;
Texture2D characterTexture;
Texture2D goalTexture;
Texture2D enemyTexture;
Texture2D staticEnemyTexture;
Song backgroundMusic;
SpriteFont font;
Grid grid;
Player player;
Rectangle spawnPoint;
Goal goal;
StartAndGoalPlacer startAndGoalPlacer;
EnemySpawner enemySpawner;
HealthCounter hpCounter;
PitfallSpawner pitfallSpawner;
Settings settings;
List<Enemy> allEnemies;
string seed;
string originalSeed;
int blockHeight;
int blockWidth;
string GameOverMessage;
int numberOfGames;
int remainingLives;
int totalLives;
int gamesWon;
bool musicIsPlaying;
GameState gameState;
KeyboardState previousState;
//Create map parameters
int mapWidth = 64;
int mapHeight = 16;
bool useCopy = true;
Rectangle StageArea;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsFixedTimeStep = false;
//graphics.SynchronizeWithVerticalRetrace = false; //this unlocks the fps, which makes movement unreliable
}
/// <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()
{
// TODO: Add your initialization logic here
settings = PredefinedSettings.settings2;
// Set your seed.
seed = settings.Seed;
originalSeed = seed;
// Sets the window-size
graphics.IsFullScreen = true;
if (graphics.IsFullScreen)
{
graphics.PreferredBackBufferWidth = GraphicsDevice.DisplayMode.Width;
graphics.PreferredBackBufferHeight = GraphicsDevice.DisplayMode.Height;
}
else
{
graphics.PreferredBackBufferWidth = GraphicsDevice.DisplayMode.Width - 100;
graphics.PreferredBackBufferHeight = GraphicsDevice.DisplayMode.Height / 2;
}
graphics.ApplyChanges();
//Sets the block size
blockHeight = 20;
blockWidth = 20;
camera = new Camera(GraphicsDevice.Viewport);
GameOverMessage = "";
numberOfGames = 0;
totalLives = 0;
remainingLives = 0;
gamesWon = 0;
gameState = GameState.MainMenu;
musicIsPlaying = false;
MediaPlayer.IsRepeating = true;
StageArea = new Rectangle(0, 0, mapWidth * blockWidth, mapHeight * blockHeight);
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);
font = Content.Load<SpriteFont>("Font");
backgroundMusic = Content.Load<Song>("cave-music");
hpCounter = new HealthCounter(spriteBatch, font);
block = CreateTexture(graphics.GraphicsDevice, blockWidth, blockHeight, pixel => Color.White);
characterTexture = Content.Load<Texture2D>("sprite-girl");
enemyTexture = Content.Load<Texture2D>("enemy");
staticEnemyTexture = Content.Load<Texture2D>("static-enemy");
goalTexture = CreateTexture(graphics.GraphicsDevice, blockWidth, blockHeight, pixel => Color.Gold);
spawnPoint = new Rectangle(new Point(graphics.GraphicsDevice.Viewport.Width / 2, graphics.GraphicsDevice.Viewport.Height / 2), new Point(characterTexture.Width, characterTexture.Height));
goal = new Goal(new Vector2(0, 0), goalTexture, spriteBatch);
CreateMap(mapWidth, mapHeight, useCopyOfMap: useCopy);
frameCounter = new FrameCounter();
if (!musicIsPlaying)
{
MediaPlayer.Play(backgroundMusic);
musicIsPlaying = true;
}
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific 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)
{
UpdateUniversal(gameTime);
switch (gameState)
{
case GameState.MainMenu:
UpdateMainMenu(gameTime);
break;
case GameState.Playing:
UpdateGameplay(gameTime);
break;
case GameState.GameOver:
UpdateEndOfGame(gameTime);
break;
case GameState.StatScreen:
UpdateStatScreen(gameTime);
break;
case GameState.Tutorial:
UpdateTutorial(gameTime);
break;
case GameState.Story:
UpdateStory(gameTime);
break;
}
base.Update(gameTime);
}
private void UpdateUniversal(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
if (Keyboard.GetState().IsKeyDown(Keys.M) && !previousState.IsKeyDown(Keys.M))
{
if (musicIsPlaying == false)
{
MediaPlayer.Resume();
musicIsPlaying = true;
}
else
{
MediaPlayer.Pause();
musicIsPlaying = false;
}
}
previousState = Keyboard.GetState();
}
/// <summary>
/// This is the update loop for the main menu
/// </summary>
/// <param name="gameTime"></param>
private void UpdateMainMenu(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Enter))
{
//CreateMap(mapWidth, mapHeight, useCopyOfMap: useCopy);
gameState = GameState.Playing;
}
if (Keyboard.GetState().IsKeyDown(Keys.T))
{
gameState = GameState.Tutorial;
}
if (Keyboard.GetState().IsKeyDown(Keys.S))
{
gameState = GameState.Story;
}
}
/// <summary>
/// Update loop for playing the game.
/// </summary>
/// <param name="gameTime"></param>
private void UpdateGameplay(GameTime gameTime)
{
Enemy EnemyToBeDeleted = null;
if (goal.BoundingRectangle.Intersects(player.BoundingRectangle))
{
GameOverMessage = "You Win!";
gameState = GameState.GameOver;
}
// TODO: Add your update logic here
hpCounter.Update(player.GetHp());
player.Update(gameTime);
camera.Update(gameTime, player);
if (!player.IsInsideStage(StageArea))
{
while (player.IsAlive())
player.DealDamage();
GameOverMessage = "You Lose!";
gameState = GameState.GameOver;
}
foreach (var enemy in allEnemies)
{
enemy.Update(gameTime);
if (!enemy.IsInsideStage(StageArea))
{
EnemyToBeDeleted = enemy;
}
if (player.BoundingRectangle.Intersects(enemy.BoundingRectangle))
{
if (!player.hurt)
{
player.DealDamage();
}
}
}
if (EnemyToBeDeleted != null)
{
allEnemies.Remove(EnemyToBeDeleted);
EnemyToBeDeleted = null;
}
if (!player.IsAlive())
{
GameOverMessage = "You Lose!";
gameState = GameState.GameOver;
}
}
/// <summary>
/// The update loop for the end of game screen
/// </summary>
/// <param name="gameTime"></param>
private void UpdateEndOfGame(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Enter))
{
if (numberOfGames < 4)
{
GetStats();
if (settings.IncrementDifficulty && remainingLives >= 2)
{
DifficultyIncrementer.Increment(settings, seed);
}
RestartGame();
}
else if (numberOfGames == 4)
{
GetStats();
gameState = GameState.StatScreen;
}
else gameState = GameState.GameOver;
}
}
private void UpdateStatScreen(GameTime gameTime)
{
//if(Keyboard.GetState().IsKeyDown(Keys.Escape)) SaveStatsToFile("TestPlayer");
musicIsPlaying = false;
MediaPlayer.Stop();
}
private void UpdateTutorial(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Keys.Enter))
{
gameState = GameState.MainMenu;
}
}
private void UpdateStory(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Keys.Enter))
{
gameState = GameState.MainMenu;
}
}
/// <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.Black);
switch (gameState)
{
case GameState.MainMenu:
DrawMainMenu(gameTime);
break;
case GameState.Playing:
DrawGamePlay(gameTime);
break;
case GameState.GameOver:
DrawEndOfGame(gameTime);
break;
case GameState.StatScreen:
DrawStatScreen(gameTime);
break;
case GameState.Tutorial:
DrawTutorial(gameTime);
break;
case GameState.Story:
DrawStory(gameTime);
break;
}
base.Draw(gameTime);
}
private void DrawMainMenu(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.DrawString(font, "Press Enter to start game", new Vector2(200, 200), Color.Navy);
spriteBatch.DrawString(font, "Press T for tutorial", new Vector2(200, 250), Color.Navy);
spriteBatch.DrawString(font, "Press S to see the story", new Vector2(200, 300), Color.Navy);
spriteBatch.DrawString(font, "Press Esc to exit game", new Vector2(200, 350), Color.Navy);
spriteBatch.DrawString(font, "Nick & Simon 2018", new Vector2(200, 450), Color.Navy);
spriteBatch.End();
}
private void DrawGamePlay(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
// TODO: Add your drawing code here
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, camera.transform);
grid.Draw(gameTime);
player.Draw(gameTime);
goal.Draw(gameTime);
hpCounter.Draw(player.Position);
frameCounter.Draw(gameTime, Window);
foreach (var enemy in allEnemies)
{
enemy.Draw(gameTime);
}
spriteBatch.End();
}
private void DrawEndOfGame(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
// TODO: Add your drawing code here
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, camera.transform);
grid.Draw(gameTime);
player.Draw(gameTime);
goal.Draw(gameTime);
foreach (var enemy in allEnemies)
{
enemy.Draw(gameTime);
}
if (!GameOverMessage.Equals(""))
{
spriteBatch.DrawString(font, GameOverMessage, new Vector2(player.Position.X, player.Position.Y - 50), Color.Navy);
spriteBatch.DrawString(font, "Game " + (numberOfGames + 1) + " of 5 ", new Vector2(player.Position.X + 250, player.Position.Y - 50), Color.Navy);
spriteBatch.DrawString(font, "Press enter to continue", new Vector2(player.Position.X, player.Position.Y), Color.Navy);
spriteBatch.DrawString(font, "Press Esc to exit game", new Vector2(player.Position.X, player.Position.Y + 50), Color.Navy);
}
spriteBatch.End();
}
private void DrawStatScreen(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
// TODO: Add your drawing code here
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, camera.transform);
spriteBatch.DrawString(font, "You won " + gamesWon + " games out of 5!", new Vector2(player.Position.X, player.Position.Y - 50), Color.Navy);
spriteBatch.DrawString(font, "You got " + totalLives + " points!", new Vector2(player.Position.X, player.Position.Y), Color.Navy);
spriteBatch.DrawString(font, "Press Esc to exit game", new Vector2(player.Position.X, player.Position.Y + 50), Color.Navy);
spriteBatch.DrawString(font, "Music by KyBOz / www.oreitia.com", new Vector2(player.Position.X, player.Position.Y + 100), Color.Navy);
spriteBatch.End();
}
private void DrawTutorial(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.DrawString(font, "Use arrow keys to move or left thumbstick on controllers", new Vector2(100, 50), Color.Navy);
spriteBatch.DrawString(font, "Press Up arrow, Space or A on controllers to jump", new Vector2(100, 100), Color.Navy);
spriteBatch.DrawString(font, "Hold X or RT on controllers and jump to perform", new Vector2(100, 150), Color.Navy);
spriteBatch.DrawString(font, "a super jump(This drains 1 health)", new Vector2(100, 200), Color.Navy);
spriteBatch.DrawString(font, "Hold Z to do a slow jump(half the jumping height)", new Vector2(100, 250), Color.Navy);
spriteBatch.DrawString(font, "Press M to mute the music", new Vector2(100, 300), Color.Navy);
spriteBatch.DrawString(font, "Press Q to skip current level", new Vector2(100, 350), Color.Navy);
spriteBatch.DrawString(font, "Press Esc to exit the game at any time", new Vector2(100, 400), Color.Navy);
spriteBatch.DrawString(font, "Press Enter to play the game", new Vector2(100, 450), Color.Navy);
spriteBatch.End();
}
private void DrawStory(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.DrawString(font, "I have never seen the sky. We were born in these caverns, deep benath ", new Vector2(25, 25), Color.Navy);
spriteBatch.DrawString(font, "the surface. Our parents would speak of a great calamity up above, ", new Vector2(25, 75), Color.Navy);
spriteBatch.DrawString(font, "but we were too young to understand the warnings in their tales. ", new Vector2(25, 125), Color.Navy);
spriteBatch.DrawString(font, "My sisters sought to see the outside world and one by one wandered ", new Vector2(25, 175), Color.Navy);
spriteBatch.DrawString(font, "up to the tunnels we were forbidden to walk, towards the exit.", new Vector2(25, 225), Color.Navy);
spriteBatch.DrawString(font, "But when they returned they were no longer themselves, ", new Vector2(25, 275), Color.Navy);
spriteBatch.DrawString(font, "but something much more sinister. ", new Vector2(25, 325), Color.Navy);
spriteBatch.DrawString(font, "I know not what caused them to transform, but the depths ", new Vector2(25, 375), Color.Navy);
spriteBatch.DrawString(font, "of the underground has kept me safe, and if there is ", new Vector2(25, 425), Color.Navy);
spriteBatch.DrawString(font, "a way to turn them back it is to be found here beneath the surface.", new Vector2(25, 475), Color.Navy);
spriteBatch.DrawString(font, "So I venture deeper and deeper in the hopes of finding the source, ", new Vector2(25, 525), Color.Navy);
spriteBatch.DrawString(font, "that which has protected me, for only I remain.", new Vector2(25, 575), Color.Navy);
spriteBatch.DrawString(font, "We are the cave generation, and once more these caves shall be ", new Vector2(25, 625), Color.Navy);
spriteBatch.DrawString(font, "our salvation.", new Vector2(25, 675), Color.Navy);
spriteBatch.DrawString(font, "Press Enter to play the game", new Vector2(25, 725), Color.Navy);
spriteBatch.End();
}
private static Texture2D CreateTexture(GraphicsDevice device, int width, int height, System.Func<int, Color> paint)
{
//initialize a texture
Texture2D texture = new Texture2D(device, width, height);
//the array holds the color for each pixel in the texture
Color[] data = new Color[width * height];
for (int pixel = 0; pixel < data.Count(); pixel++)
{
//the function applies the color according to the specified pixel
data[pixel] = paint(pixel);
}
//set the color
texture.SetData(data);
return texture;
}
/// <summary>
/// This method crates a new map to let the player play the game again.
/// </summary>
private void RestartGame()
{
numberOfGames++;
CreateMap(mapWidth, mapHeight, useCopy);
gameState = GameState.Playing;
}
/// <summary>
/// This method gets the stats from your current game and adds them to total stats
/// </summary>
private void GetStats()
{
remainingLives = player.GetHp();
totalLives += remainingLives;
if (GameOverMessage.Equals("You Win!"))
{
gamesWon++;
}
}
/*
private void SaveStatsToFile(string playername)
{
StorageHandler storage = new StorageHandler();
storage.SaveStatsToStorage(playername, totalLives);
}
*/
private void CreateMap(int mapWidthInBlocks, int mapHeightInBlocks, bool useCopyOfMap)
{
bool solveable = true;
do
{
Grid.ClearInstance();
grid = Grid.CreateNewGrid(mapWidthInBlocks, mapHeightInBlocks, spriteBatch, block, seed, settings);
pitfallSpawner = new PitfallSpawner(settings);
pitfallSpawner.GeneratePitfalls();
startAndGoalPlacer = new StartAndGoalPlacer(goal, characterTexture, graphics, settings);
enemySpawner = new EnemySpawner(settings, enemyTexture, staticEnemyTexture, spriteBatch);
spawnPoint = startAndGoalPlacer.GetSpawnPosition();
enemySpawner.RunEnemySpawner(spawnPoint);
player = new Player(characterTexture, new Vector2(spawnPoint.X, spawnPoint.Y), spriteBatch, settings);
startAndGoalPlacer.SetPlayer(player);
allEnemies = enemySpawner.GetEnemies();
try
{
goal = startAndGoalPlacer.GenerateReachableGoalPosition();
solveable = true;
}
catch (NotSolveableException ex)
{
//if the map is not solveable we generate a new random seed and try again
if (ex.Message.Equals("Not solveable"))
{
solveable = false;
Console.WriteLine(seed);
Console.WriteLine(originalSeed);
int tmp;
if (!originalSeed.Equals(""))
{
tmp = new Random(seed.GetHashCode()).Next();
}
else
{
tmp = new Random().Next();
}
seed = tmp.GetHashCode().ToString();
}
}
}
while (!solveable);
}
}
}
|
namespace Fingo.Auth.DbAccess.Models.Statuses
{
public enum UserStatus
{
Active = 0 ,
Deleted = 1 ,
Registered = 2 ,
AccountCreated
}
} |
namespace MetroBlog.Web.ViewModels
{
using System;
using System.Collections.Generic;
/// <summary>
/// Defines a view model for the post summaries list
/// </summary>
public class PostSummaryListViewModel
{
private readonly List<PostSummaryViewModel> postsList = new List<PostSummaryViewModel>();
/// <summary>
/// Gets the list of posts
/// </summary>
public IEnumerable<PostSummaryViewModel> PostsList
{
get
{
return this.postsList;
}
}
/// <summary>
/// Adds a post in the collection of posts
/// </summary>
/// <param name="post">The post to add</param>
public void AddPost(Domain.Entities.Post post)
{
this.postsList.Add(new PostSummaryViewModel(post));
}
}
} |
using System;
namespace AssemblyResolver.QuickStart.Sample
{
/// <summary>
/// Class TestClass.
/// </summary>
public class TestClass
{
/// <summary>
/// Outputs the message.
/// </summary>
public void OutputMessage()
{
Console.WriteLine("Hello world!");
}
}
} |
/*******************************************
*
* This class should only control Modules that involves Player Air Controls
* NO CALCULATIONS SHOULD BE DONE HERE
*
*******************************************/
using UnityEngine;
namespace DChild.Gameplay.Player.Controllers
{
[System.Serializable]
public class DoubleJumpController : PlayerControllerManager.Controller
{
private IDoubleJump m_doubleJump;
private bool m_hasDoubleJump;
public bool hasDoubleJump => m_hasDoubleJump;
public bool doneDoubleJumping { get; set; }
public override void Initialize() => m_doubleJump = m_player.GetComponentInChildren<IDoubleJump>();
public void HandleDoubleJump()
{
if (m_input.isJumpPressed)
{
m_hasDoubleJump = m_doubleJump.Jump(true);
if (m_hasDoubleJump)
{
m_player.animation.DoDoubleJump();
doneDoubleJumping = true;
}
}
else
{
m_hasDoubleJump = false;
}
}
public void Reset() => m_doubleJump.ResetSkill();
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using CompanyEmployees.Extensions;
using Contracts;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Localization.Routing;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NLog;
using PhysicalPersons.Extensions;
using PhysicalPersons.Filters;
namespace PhysicalPersons
{
public class Startup
{
public Startup(IConfiguration configuration)
{
LogManager.LoadConfiguration(string.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(
options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("ka-GE")
};
options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture(culture: "en-US", uiCulture: "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
services.ConfigureCors();
services.ConfigureIISIntegration();
services.ConfigureLoggerService();
services.ConfigureSqlContext(Configuration);
services.ConfigureUnitOfWork();
services.ConfigureProjectServices();
services.ConfigureSwagger();
//For returning 422 response on model validation issues
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.AddAutoMapper(typeof(Services.MappingProfile));
services.AddControllers(config =>
{
config.Filters.Add(new ValidationActionFilter());
}).AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
//var assemblyName = new AssemblyName(typeof(Entities.DTOs.CreationDtos.PhoneNumberForCreationDto).GetTypeInfo().Assembly.FullName);
return factory.Create("Translations", "Entities");
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerManager logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.ConfigureExceptionHandler(logger);
app.UseHttpsRedirection();
var localizeOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(localizeOptions.Value);
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseSwagger();
app.UseSwaggerUI(s =>
{
s.SwaggerEndpoint("/swagger/v1/swagger.json", "Physical Persons Api v1");
});
//Forward proxy headers to current request. Will Be Useful during deployment.
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.All
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleUI
{
class Program
{
static void Main(string[] args)
{
var vehicles = new List<Vehicle>();
var juansCar = new Car() {Year=2021 , Make="Ford" , Model="Explorer" };
var juansMotorcycle = new Motorcycle() { Year = 2019, Make = "Harley", Model = "Kt500" };
Vehicle juanOneVehicle = new Car() { Year = 2017, Make = "Toyota", Model = "Camry" };
Vehicle juanTwoVehicle = new Motorcycle() { Year = 2015, Make = "Honda", Model = "Ninja300" };
vehicles.Add(juansCar);
vehicles.Add(juansMotorcycle);
vehicles.Add(juanOneVehicle);
vehicles.Add(juanTwoVehicle);
foreach(var vehicle in vehicles)
{
Console.WriteLine($"My {vehicle.Model} it's mark is {vehicle.Make} and it is of {vehicle.Year}");
}
juansCar.DriveAbstract();
juansCar.DriveVirtual();
juansMotorcycle.DriveAbstract();
juansMotorcycle.DriveVirtual();
juanOneVehicle.DriveAbstract();
juanOneVehicle.DriveVirtual();
juanTwoVehicle.DriveAbstract();
juanTwoVehicle.DriveVirtual();
/*
* Todo follow all comments!!
*/
#region Vehicles
// Create a list of Vehicle called vehicles
/*
* Create 4 instances: 1 Car, 1 Motorcycle, and then 2 instances of type Vehicle (use explicit typing) but use constuctors from derived classes
* - new it up as one of each derived class
* Set the properties with object initializer syntax
*/
/*
* Add the 4 vehicles to the list
* Using a foreach loop iterate over each of the properties
*/
// Call each of the drive methods for one car and one motorcycle
#endregion
Console.ReadLine();
}
}
}
|
using UnityEngine;
using UnityEngine.Rendering;
namespace DChild
{
[RequireComponent(typeof(MeshRenderer))]
public class RenderOrder3D : MonoBehaviour
{
[SerializeField][SortingLayer]
private int m_sortingLayer;
[SerializeField]
private int m_sortingOrder;
private void Awake()
{
var renderer = GetComponent<MeshRenderer>();
renderer.sortingLayerID = m_sortingLayer;
renderer.sortingOrder = m_sortingOrder;
}
private void OnValidate()
{
var sortingGroup = GetComponent<SortingGroup>();
if(sortingGroup != null)
{
m_sortingLayer = sortingGroup.sortingLayerID;
m_sortingOrder = sortingGroup.sortingOrder;
}
var renderer = GetComponent<MeshRenderer>();
renderer.sortingLayerID = m_sortingLayer;
renderer.sortingOrder = m_sortingOrder;
}
}
} |
using System;
namespace _11_Self_Operator_overload
{
public abstract class Product
{
public string Name { get;}
public int Colories { get;}
public int Volume { get; set; }
public double totalColories
{
get
{
return Volume / 100 * Colories;
}
}
public Product(string name, int colories, int volume) // конструктор
{
//проверка входных параметров
if (string.IsNullOrWhiteSpace (name))
{
throw new ArgumentNullException(nameof(name));
}
if (colories < 0)
{
throw new ArgumentException(nameof(colories));
}
if (volume <= 0)
{
throw new ArgumentException(nameof(volume));
}
Name = name;
Colories = colories;
Volume = volume;
}
public override string ToString()
{
return $"{Name} - {Volume}: {Colories}";
}
}
}
|
using System;
using AxisPosCore;
using AxisPosCore.Common;
using KartObjects;
namespace AxisPosCore.ActionExecutors
{
public class CloseReceiptActionExecutor : POSActionExecutor
{
public CloseReceiptActionExecutor(POSActionMnemonic action)
: base(action)
{
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.SubTotal);
}
public CloseReceiptActionExecutor()
{
ValidRegistrationModes.Add(POSRegistrationState.RegistrationStateMode.SubTotal);
}
protected override void InnerExecute(PosCore model, params object[] args)
{
decimal buyerSum;
if (args[0].ToString() == "")
{
buyerSum = POSEnvironment.CurrReceipt.TotalSum - POSEnvironment.CurrReceipt.SumPaymentDiscount;
}
else if (
!Decimal.TryParse(args[0].ToString().Replace(",", decimalSeparator).Replace(".", decimalSeparator),
out buyerSum))
throw new POSException("Неправильный формат вводимых данных!");
if (buyerSum > DataDictionary.SPosParameters[PosParameterType.MaxReceiptSum].decimalValue)
throw new POSException("Число превышает предельно допустимое!");
if (buyerSum < 0) throw new POSException("Сумма оплаты не может быть отрицательным числом!");
//
//if (BuyerSum < POSEnvironment.CurrReceipt.TotalSum) throw new POSException("Вводимая сумма меньше суммы чека!");
//Добавляем оплату
if ((buyerSum >=
POSEnvironment.CurrReceipt.UnpaidRest +
POSEnvironment.CurrReceipt.SumOfPayment(model.RegistrationState.CurrPayType)) &&
(POSEnvironment.CurrReceipt.UnpaidRest >= 0))
POSEnvironment.CurrReceipt.AddPayment(model.RegistrationState.CurrPayType,
POSEnvironment.CurrReceipt.UnpaidRest +
POSEnvironment.CurrReceipt.SumOfPayment(model.RegistrationState.CurrPayType));
else
POSEnvironment.CurrReceipt.AddPayment(model.RegistrationState.CurrPayType, buyerSum);
POSEnvironment.SendEvent(
model.RegistrationState.CurrPayType.PayTypeInfo == PayTypeInfo.Cash
? TypeExtEvent.eeCashPayment
: TypeExtEvent.eeCashlessPayment,
POSEnvironment.CurrReceipt.SumOfPayment(model.RegistrationState.CurrPayType));
//Сохраняем чек с оплатой
model.PosEnvironment.SaveCurrReceipt();
//Для смешанной оплаты
if (POSEnvironment.CurrReceipt.UnpaidRest > 0)
{
model.RegistrationState.StateMode = POSRegistrationState.RegistrationStateMode.SubTotal;
throw new POSException("Необходимо доплатить " + POSEnvironment.CurrReceipt.UnpaidRest);
}
POSEnvironment.CurrReceipt.BuyerSum = buyerSum +
POSEnvironment.CurrReceipt.SumExceptPayment(
model.RegistrationState.CurrPayType);
//Логика запрета начисления бонусов, если была оплата CLM
if (POSEnvironment.CurrReceipt.HasCLMPayment)
{
if (DataDictionary.GetParamBoolValue(PosParameterType.DisableBonusChargeOnCLMPayment))
POSEnvironment.CurrReceipt.NeedBonusCharge = false;
}
//Проверяем карту на дисконтную, если да то запрет начисления бонусов на чек
if ((POSEnvironment.CurrReceipt.CustomerCardCode != null) && (POSEnvironment.CurrReceipt.NeedBonusCharge))
POSEnvironment.CurrReceipt.NeedBonusCharge =
DataDictionary.GetCardByCode(POSEnvironment.CurrReceipt.CustomerCardCode) == null;
//Если чек не завис
if (POSEnvironment.CurrReceipt.ReceiptState != ReceiptState.Hanged)
{
POSEnvironment.AcquiringEo.DoPrePayment(POSEnvironment.CurrReceipt);
int paymentError = POSEnvironment.AcquiringEo.DoPayment(POSEnvironment.CurrReceipt);
if (paymentError != 0)
{
//Если не прошла оплата отменяем предыдущие начисления бонусов
POSEnvironment.AcquiringEo.DoEmergencyCancelPrePayment(POSEnvironment.CurrReceipt);
throw new POSException("Ошибка оплаты " + paymentError);
}
}
POSEnvironment.Change = POSEnvironment.CurrReceipt.Change;
model.RegistrationState.ChangeState();
model.RegistrationState.StateMode = POSRegistrationState.RegistrationStateMode.ClosingDoc;
if (POSEnvironment.PrinterEo.CloseReceipt(POSEnvironment.CurrReceipt))
{
//Отправляем события
POSEnvironment.SendEvent(
POSEnvironment.CurrReceipt.DirectOperation == 1
? TypeExtEvent.eeEndCheck
: TypeExtEvent.eeEndRetCheck, POSEnvironment.CurrReceipt);
//Закрываем чек, очищаем переменные
model.PosEnvironment.CloseReceipt();
if (DataDictionary.GetParamBoolValue(PosParameterType.RefreshCustomerDisplayAfterRClose))
POSEnvironment.CustomerDisplayEo.ShowWelcomeMessage();
POSEnvironment.SendEvent(TypeExtEvent.eePrintCheck);
model.RegistrationState.StateMode = POSRegistrationState.RegistrationStateMode.Idle;
}
else
{
POSEnvironment.SendEvent(TypeExtEvent.eePrinterError);
model.RegistrationState.StateMode = POSRegistrationState.RegistrationStateMode.SubTotal;
if ((POSEnvironment.CurrReceipt.ReceiptState != ReceiptState.Hanged) &&
(POSEnvironment.CurrReceipt.ReceiptState != ReceiptState.KPKConfirmationUnknown))
{
POSEnvironment.AcquiringEo.DoEmergencyCancelPrePayment(POSEnvironment.CurrReceipt);
POSEnvironment.AcquiringEo.DoEmergencyCancel(POSEnvironment.CurrReceipt);
}
if (POSEnvironment.CurrReceipt.ReceiptState == ReceiptState.KPKConfirmationUnknown)
{
model.RegistrationState.StateMode =
POSRegistrationState.RegistrationStateMode.KPKConfirmationUnknown;
model.PosEnvironment.SaveCurrReceipt();
model.PosEnvironment.SaveCurrReport();
}
}
}
}
} |
using BattleEngine.Utils;
namespace BattleEngine.Actors.Damages
{
public class BattleDamage : BattleObject
{
private int _tick;
private int _deltaTick;
public BattleDamage()
{
}
public int tick
{
get { return _tick; }
}
public virtual void update(int tick, int deltaTick)
{
_tick = tick;
_deltaTick = deltaTick;
}
public virtual Vector<ApplyDamageResult> applyDamage(int tick, Vector<ApplyDamageResult> result = null)
{
return result;
}
public virtual bool needApplyDamage
{
get { return false; }
}
public virtual bool needRemove
{
get { return true; }
}
public int deltaTick
{
get
{
return _deltaTick;
}
}
}
}
|
using YesSql.Indexes;
namespace DFC.ServiceTaxonomy.JobProfiles.DataTransfer.Indexes
{
public class JobProfileIndex : MapIndex
{
public string? ContentItemId { get; set; }
public string? GraphSyncPartId { get; set; }
public string? DynamicTitlePrefix { get; set; }
public string? JobProfileSpecialism { get; set; }
public string? JobProfileCategory { get; set; }
public string? RelatedCareerProfiles { get; set; }
public string? SOCCode { get; set; }
public string? HiddenAlternativeTitle { get; set; }
public string? WorkingHoursDetail { get; set; }
public string? WorkingPatterns { get; set; }
public string? WorkingPatternDetail { get; set; }
public string? UniversityEntryRequirements { get; set; }
public string? UniversityRequirements { get; set; }
public string? UniversityLinks { get; set; }
public string? CollegeEntryRequirements { get; set; }
public string? CollegeRequirements { get; set; }
public string? CollegeLink { get; set; }
public string? ApprenticeshipEntryRequirements { get; set; }
public string? ApprenticeshipRequirements { get; set; }
public string? ApprenticeshipLink { get; set; }
public string? Registration { get; set; }
public string? DigitalSkills { get; set; }
public string? RelatedSkills { get; set; }
public string? Location { get; set; }
public string? Environment { get; set; }
public string? Uniform { get; set; }
public string? JobProfileTitle { get; set; }
public string? Restriction { get; set; }
}
}
|
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 WatiN.Core;
namespace WebAutomation
{
public partial class Search_Controls : System.Windows.Forms.Form
{
public Search_Controls()
{
InitializeComponent();
}
private void btnGetTargetFrame_Click(object sender, EventArgs e)
{
btnGetTargetFrame.Enabled = false;
IE ie = Core.IdentifyWebPage(txtTitle.Text, "");
if (ie == null)
{
UIHelper.StopMessage("Cannot identify the webpage");
txtTitle.Focus();
return;
}
int totalFrames = ie.Frames.Count;
txtPageFrame.Clear();
if (dnSearchBy.Text.ToLower() == "name")
{
var obj = ie.Element(Find.ByName(txtTargetControl.Text));
if (obj.Exists == true)
{
MessageBox.Show("Found");
obj.Flash(2);
return;
}
}
if (totalFrames > 1)
{
for (int i = 0; i < totalFrames; i++)
{
if (dnSearchBy.Text.ToLower() == "id")
{
var idObj = ie.Frames[i].Element(Find.ById(txtTargetControl.Text));
if (idObj.Exists == true)
{
txtPageFrame.Text = i.ToString();
idObj.Flash(2);
break;
}
}
else if (dnSearchBy.Text.ToLower() == "name")
{
var nameObj = ie.Frames[i].Element(Find.ByName(txtTargetControl.Text));
if (nameObj.Exists == true)
{
txtPageFrame.Text = i.ToString();
nameObj.Flash(2);
break;
}
}
else if (dnSearchBy.Text.ToLower() == "text")
{
var txtObj = ie.Frames[i].Element(Find.ByText(txtTargetControl.Text));
if (txtObj.Exists == true)
{
txtPageFrame.Text = i.ToString();
txtObj.Flash(2);
txtObj.Focus();
SendKeys.SendWait("{ENTER}");
break;
}
}
}
if (txtPageFrame.Text.Length == 0)
{
UIHelper.StopMessage("Control not found");
}
else
{
UIHelper.ShowMessage("Control found on the web page", "Search control");
}
}
else
{
Boolean found = false;
if (dnSearchBy.Text.ToLower() == "id")
{
if (ie.Element(Find.ById(txtTargetControl.Text)).Exists == true)
{
ie.Element(Find.ById(txtTargetControl.Text)).Flash(2);
found = true;
}
}
else if (dnSearchBy.Text.ToLower() == "name")
{
if (ie.Element(Find.ByName(txtTargetControl.Text)).Exists == true)
{
ie.Element(Find.ById(txtTargetControl.Text)).Flash(2);
found = true;
}
}
else if (dnSearchBy.Text.ToLower() == "text")
{
if (ie.Element(Find.ByText(txtTargetControl.Text)).Exists == true)
{
ie.Element(Find.ByText(txtTargetControl.Text)).Flash(2);
found = true;
}
}
if (found == false)
{
UIHelper.StopMessage("Control not found");
}
else
{
UIHelper.ShowMessage("Control found on the web page", "Search control");
}
}
btnGetTargetFrame.Enabled = true;
}
private void btnApply_Click(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
class Student // Создаем класс с именем "Student"
{
private string name; // имя студента
private string id; // ID студента
private int yearofstudy; // год обучения студента
public Student(string name, string id) // Создаем конструктор с двумя параметрами
{
this.name = name; // вводится имя this пишется чтобы компилятор не перепутал переменные
this.id = id; // вводится id
}
public void Increment() // Метод для инкрементирования года обучения обьекта Студента
{
yearofstudy++;
}
public int YearofStudy // Это делается для доступа в приватному свойству yearofstudy
{
get
{
return yearofstudy;
}
set
{
yearofstudy = value;
}
}
}
static void Main(string[] args)
{
Student s = new Student("Yerlan", "18BD110739"); // создаем обьект класса Студент
s.YearofStudy = 1; // по умолчанию значение равно 1
s.Increment(); // после мметода значение инкрементируется (+1), то есть равно 2
Console.WriteLine(s.YearofStudy); // Показываю, что метод Increment работает (Вывод: 2)
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAppMVC.DTO
{
public class MovieDTO
{
}
} |
using UnityEngine;
using UnityEngine.UI;
public class UiPokemonInfoCell : MonoBehaviour
{
[SerializeField] private Image _pokemonIcon;
[SerializeField] private Text _pokemonName;
[SerializeField] private Text _pokemonId;
public void Set(Response.PokemonInfo data)
{
_pokemonId.text = string.Format(Localization.Instance.Get("id"), data.url.Replace("https://pokeapi.co/api/v2/pokemon/", "").Replace("/", ""));
_pokemonName.text = string.Format(Localization.Instance.Get("name"), data.name.FirstLetterToUpperCase());
_pokemonIcon.sprite = Resources.Load<Sprite>($"{GameConfig.Instance.pokemonIconsPath}PokemonIcon_{Random.Range(0, 4)}");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Btf.Data.Model.User;
namespace Btf.Data.Contracts.Interfaces
{
public interface ILocationRepository : IRepository<City>
{
IQueryable<Country> GetCountries();
IQueryable<State> GetStates(int countryId);
IQueryable<City> GetCities(int cityId);
Task<List<City>> GetAllCitites();
Task<State> GetStateByCityId(int cityId);
Task<Country> GetCountryByStateId(int stateId);
Task<List<State>> GetStatesByNameAsync(string stateName);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Reflection;
using System.Text.RegularExpressions;
using Serialization.Configuration;
namespace Serialization.Mappers
{
public class ManyToOneMapper : PropertyMapperBase
{
[XmlAttribute("class")]
public string ClassName { get; set; }
[XmlIgnore]
public bool ClassNameSpecified { get; set; }
[XmlAttribute("property")]
public string PropertyName { get; set; }
[XmlIgnore]
public bool PropertyNameSpecified { get; set; }
[XmlElement("substitution")]
public Substitution<string>[] Substitutions { get; set; }
public string GetSubstitution(string old)
{
if (Substitutions.Any(s => s.Key == old && !s.IsRegularExpression))
return Substitutions.First(s => s.Key == old).Value;
if (Substitutions.Any(s => s.IsRegularExpression && Regex.IsMatch(old, s.Key)))
{
var substitution = Substitutions.First(s => s.IsRegularExpression && Regex.IsMatch(old, s.Key));
if (Regex.Match(old, substitution.Key).Groups.Count > 1)
return Regex.Replace(old, substitution.Key, substitution.Value);
else
return substitution.Value;
}
throw new KeyNotFoundException(string.Format("Não foi encontrada uma substituição para '{0}'.", old));
}
private Type _mappedType;
[XmlIgnore]
public override Type MappedType
{
get
{
if (_mappedType != null)
return _mappedType;
Assembly.Load(TextMapping.DefaultAssembly);
if (!ClassNameSpecified)
_mappedType = TextMapping.MappedType.GetProperty(this.Name).PropertyType;
else
{
string typeName = new TypeHelper()
.GetFullTypeName(
ClassName,
TextMapping.DefaultNamespace,
TextMapping.DefaultAssembly);
_mappedType = Type.GetType(typeName, false, false);
if (_mappedType == null)
throw new InvalidCastException("Wrong class to map.");
}
return _mappedType;
}
}
}
}
|
using Microsoft.EntityFrameworkCore;
namespace SpacePort.Models
{
public class SpacePortContext : DbContext
{
public virtual DbSet<Port> Ports { get; set; }
public virtual DbSet<Vessel> Vessels { get; set; }
public virtual DbSet<Manifest> Manifests { get; set; }
public SpacePortContext(DbContextOptions options) : base(options) { }
}
} |
using System;
using System.Collections.Generic;
namespace HospitalSystem.Models
{
public partial class withdraw_medicine_record
{
public long WithdrawMedicineRecordID { get; set; }
public Nullable<long> MedicineID { get; set; }
public Nullable<long> PatientID { get; set; }
public Nullable<long> StaffID { get; set; }
public Nullable<int> MedicineNumber { get; set; }
public Nullable<System.DateTime> WithdrawMedicineDate { get; set; }
public virtual medicine medicine { get; set; }
public virtual patient patient { get; set; }
public virtual staff staff { get; set; }
}
}
|
using Hayaa.BaseModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
namespace Hayaa.WorkerSecurity.Client
{
public class UserAuthorityFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
bool isPost = context.HttpContext.Request.Method.ToLower().Equals("post");
var urlParamater = new Dictionary<string, string>();
String token = isPost ? context.HttpContext.Request.Form["authtoken"] : context.HttpContext.Request.Query["authtoken"];
Boolean configResult = WorkerSecurityProvider.UserAuth(token);
if (!configResult)
{
context.Result = new JsonResult(new FunctionOpenResult<bool>() {
ActionResult=false,
Data=false,
ErrorCode=403,
ErrorMsg="未登陆"
});
}
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
}
}
|
using System;
using DFC.ServiceTaxonomy.VersionComparison.Controllers;
using DFC.ServiceTaxonomy.VersionComparison.Drivers;
using DFC.ServiceTaxonomy.VersionComparison.Services;
using DFC.ServiceTaxonomy.VersionComparison.Models;
using DFC.ServiceTaxonomy.VersionComparison.Services.PropertyServices;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OrchardCore.Admin;
using OrchardCore.ContentManagement.Display.ContentDisplay;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Handlers;
using OrchardCore.Modules;
using OrchardCore.Mvc.Core.Utilities;
namespace DFC.ServiceTaxonomy.VersionComparison
{
public class Startup : StartupBase
{
private readonly AdminOptions _adminOptions;
public Startup(IOptions<AdminOptions> adminOptions)
{
_adminOptions = adminOptions.Value;
}
public override void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IDisplayManager<VersionComparisonOptions>, DisplayManager<VersionComparisonOptions>>()
.AddScoped<IDisplayDriver<VersionComparisonOptions>, VersionComparisonOptionsDisplayDriver>();
services.AddScoped<IDisplayManager<DiffItem>, DisplayManager<DiffItem>>()
.AddScoped<IDisplayDriver<DiffItem>, DiffItemDisplayDriver>();
services.AddScoped<IAuditTrailQueryService, AuditTrailQueryService>();
services.AddScoped<IDiffBuilderService, DiffBuilderService>();
services.AddScoped<IContentNameService, ContentNameService>();
services.AddScoped<IContentDisplayDriver, VersionComparisonContentsDriver>();
// Ordering of adding these services is important here, they will be processed for appropriateness in this order
services
.AddScoped<IPropertyService, NullPropertyService>()
.AddScoped<IPropertyService, BasicPropertyService>()
.AddScoped<IPropertyService, AddBannerPropertyService>()
.AddScoped<IPropertyService, PageLocationsPropertyService>()
.AddScoped<IPropertyService, WidgetPropertyService>()
.AddScoped<IPropertyService, SingleChildPropertyService>();
}
public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes,
IServiceProvider serviceProvider)
{
var adminControllerName = typeof(AdminController).ControllerName();
routes.MapAreaControllerRoute(
name: "VersionCompareIndex",
areaName: "DFC.ServiceTaxonomy.VersionComparison",
pattern: _adminOptions.AdminUrlPrefix + "/VersionComparison/{contentItemId}",
defaults: new { controller = adminControllerName, action = nameof(AdminController.Index) }
);
}
}
}
|
using UnityEngine;
using UnityEngine.Serialization;
namespace UnityAtoms.MonoHooks
{
/// <summary>
/// Generic base class for all Mono Hooks.
/// </summary>
/// <typeparam name="E">Event of type `AtomEvent<EV>`</typeparam>
/// <typeparam name="EV">Event value type</typeparam>
/// <typeparam name="F">Function type `AtomFunction<GameObject, GameObject>`</typeparam>
[EditorIcon("atom-icon-delicate")]
public abstract class MonoHook<E, EV, ER, F> : MonoBehaviour
where E : AtomEvent<EV>
where ER : IGetEvent, ISetEvent
where F : AtomFunction<GameObject, GameObject>
{
/// <summary>
/// The Event
/// </summary>
public E Event { get => _eventReference.GetEvent<E>(); set => _eventReference.SetEvent<E>(value); }
[SerializeField]
private ER _eventReference = default(ER);
/// <summary>
/// Selector function for the Event `EventWithGameObjectReference`. Makes it possible to for example select the parent GameObject and pass that a long to the `EventWithGameObjectReference`.
/// </summary>
[SerializeField]
protected F _selectGameObjectReference = default(F);
protected void OnHook(EV value)
{
if (Event != null)
{
Event.Raise(value);
}
RaiseWithGameObject(value, _selectGameObjectReference != null ? _selectGameObjectReference.Call(gameObject) : gameObject);
}
protected abstract void RaiseWithGameObject(EV value, GameObject gameObject);
}
}
|
using Backend.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using UserService.CustomException;
using UserService.Model;
namespace UserService.Repository
{
public class CityRepository : ICityRepository
{
private readonly MyDbContext _context;
public CityRepository(MyDbContext context)
{
_context = context;
}
public City Get(int id)
{
try
{
var city = _context.Cities.Find(id);
if (city is null)
throw new NotFoundException("City with the id " + id + " does not exist.");
return new City(city.ZipCode, city.Name, city.CountryId, city.Country.Name);
}
catch (UserServiceException)
{
throw;
}
catch (Exception e)
{
throw new DataStorageException(e.Message);
}
}
public IEnumerable<City> GetAll()
{
try
{
return _context.Cities.Select(
c => new City(c.ZipCode, c.Name, c.Country.Id, c.Country.Name));
}
catch (Exception e)
{
throw new DataStorageException(e.Message);
}
}
public IEnumerable<City> GetByCountry(int countryId)
{
try
{
return _context.Cities.Where(
c => c.CountryId == countryId).Select(
c => new City(c.ZipCode, c.Name, c.Country.Id, c.Country.Name));
}
catch (Exception e)
{
throw new DataStorageException(e.Message);
}
}
}
}
|
using System.ComponentModel;
using System.Linq;
using ApartmentApps.Api.Modules;
using ApartmentApps.Api.Services;
using ApartmentApps.Data;
using ApartmentApps.Data.Repository;
using ApartmentApps.Portal.Controllers;
using Ninject;
namespace ApartmentApps.Api.ViewModels
{
[DisplayName("Buildings")]
public class BuildingViewModel : BaseViewModel
{
public string Name { get; set; }
}
public class PropertyIndexBindingModel : BaseViewModel
{
public int PropertyCount { get; set; }
public string Corporation { get; set; }
public int CorporationId { get; set; }
public PropertyState Status { get; set; }
}
public class PropertyIndexMapper : BaseMapper<Property, PropertyIndexBindingModel>
{
public PropertyIndexMapper(IUserContext userContext, IModuleHelper moduleHelper) : base(userContext, moduleHelper)
{
}
public override void ToModel(PropertyIndexBindingModel viewModel, Property model)
{
model.Name = viewModel.Title;
model.CorporationId = viewModel.CorporationId;
model.State = viewModel.Status;
}
public override void ToViewModel(Property model, PropertyIndexBindingModel viewModel)
{
viewModel.Title = model.Name;
viewModel.Id = model.Id.ToString();
viewModel.Corporation = model.Corporation?.Name;
viewModel.CorporationId = model.CorporationId;
viewModel.Status = model.State;
}
}
//public class PropertyService : StandardCrudService<Property>
//{
// public PropertyService(IKernel kernel, IRepository<Property> repository) : base(kernel, repository)
// {
// }
//}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class WaveManager : MonoBehaviour
{
[SerializeField] private Wave[] wave;
[SerializeField] private Transform enemySpawnPoint;
[SerializeField] private float timeBetweenSpawn = 1f;
[SerializeField] private float timeBetweenWaves = 15f;
[SerializeField] private Image waveTimerImage;
private int waveIndex = -1;
private float countdown;
// Update is called once per frame
void Update()
{
waveTimerImage.fillAmount = countdown / timeBetweenWaves;
if (waveIndex >= wave.Length - 1) {
countdown = 0;
GameManager.WavesEnded = true;
return;
}
if (countdown <= 0f || Input.GetKeyDown(KeyCode.N)) {
StartCoroutine(SpawnWave());
countdown = timeBetweenWaves;
}
countdown -= Time.deltaTime;
countdown = Mathf.Clamp(countdown, 0f, Mathf.Infinity);
}
IEnumerator SpawnWave() {
waveIndex++;
for (int i = 0; i < wave[waveIndex].enemies.Length; i++) {
SpawnEnemy(i);
yield return new WaitForSeconds(timeBetweenSpawn);
}
}
void SpawnEnemy(int i) {
Instantiate(wave[waveIndex].enemies[i], enemySpawnPoint.position, Quaternion.identity);
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
using Caserraria.Items;
namespace Caserraria.Items.Healing
{
public class PurifiedHoney : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Purified Honey");
}
public override void SetDefaults()
{
item.useStyle = 2;
item.useTime = 17;
item.useAnimation = 17;
item.UseSound = SoundID.Item3;
item.value = 150;
item.rare = 1;
item.healLife = 115;
item.maxStack = 30;
item.consumable = true;
item.potion = true;
}
public override void AddRecipes()
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ItemID.BottledHoney, 1);
recipe.AddTile(TileID.Campfire);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
} |
using MediatR;
using MikeGrayCodes.Authentication.Application.Authentication;
using MikeGrayCodes.Authentication.Domain.Entities.ApplicationUser;
using MikeGrayCodes.BuildingBlocks.Application;
using System.Threading;
using System.Threading.Tasks;
namespace MikeGrayCodes.Authentication.Application.Users.Commands
{
internal class CreateUserCommandHandler : ICommandHandler<CreateUserCommand>
{
private readonly IApplicationUserRepository applicationUserRepository;
private readonly IApplicationUserUniquenessChecker uniquenessChecker;
public CreateUserCommandHandler(
IApplicationUserRepository applicationUserRepository,
IApplicationUserUniquenessChecker uniquenessChecker)
{
this.applicationUserRepository = applicationUserRepository ?? throw new System.ArgumentNullException(nameof(applicationUserRepository));
this.uniquenessChecker = uniquenessChecker ?? throw new System.ArgumentNullException(nameof(uniquenessChecker));
}
public async Task<Unit> Handle(CreateUserCommand request, CancellationToken cancellationToken)
{
var password = PasswordManager.HashPassword(request.Password);
var applicationUser = ApplicationUser.Create(request.Email, request.FirstName, uniquenessChecker);
await applicationUserRepository.Add(applicationUser);
return Unit.Value;
}
}
}
|
using System;
using System.Collections.Generic;
namespace Fingo.Auth.Domain.CustomData.Factories.Actions.Interfaces
{
public interface IGetUserCustomDataListFromProject
{
List<Tuple<string , string>> Invoke(Guid projectGuid , string userLogin);
}
} |
using NetEscapades.AspNetCore.SecurityHeaders.Headers;
// ReSharper disable once CheckNamespace
namespace Microsoft.AspNetCore.Builder
{
/// <summary>
/// Extension methods for adding a <see cref="ServerHeader" /> to a <see cref="HeaderPolicyCollection" />
/// </summary>
public static class RemoveCustomHeaderExtensions
{
/// <summary>
/// Remove a custom header from all requests
/// </summary>
/// <param name="policies">The collection of policies</param>
/// <param name="header">The header value to remove</param>
/// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns>
public static HeaderPolicyCollection RemoveCustomHeader(this HeaderPolicyCollection policies, string header)
{
return policies.ApplyPolicy(new RemoveCustomHeader(header));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mec.Model
{
public class BaseParam
{
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
public string OrgCode { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
//using Parse;
public class AssetDownloader : MonoBehaviour {
private const string DB_FILE = "4823754324275785482736";
private const string PARSE_TABLE_ANALYTICS = "AnalyticsDownloadData";
private const string PARSE_DATANAME_ROW = "dataName";
private const string PARSE_COUNTERS_ROW = "counters";
//"self-create-in-hierarchy" singleton type
private static AssetDownloader instance;
private static WaitForSeconds waitWhenCheckProgress = new WaitForSeconds(0.1f);
private static DownloadedAssetDatabase db;
private static bool isInitialized = false;
private static void Initialize () {
if (!isInitialized) {
db = FileUtilities.DeserializeObjectFromFile<DownloadedAssetDatabase>(DB_FILE, "tng2903");
if (db == null) {
db = new DownloadedAssetDatabase();
db.assets = new Dictionary<string, DownloadedAssetItem>();
}
isInitialized = true;
}
}
public static AssetDownloader Instance {
get {
if (instance == null) {
GameObject go = new GameObject("AssetDownloader");
instance = go.AddComponent<AssetDownloader>();
DontDestroyOnLoad(go);
}
return instance;
}
}
public void DownloadAndCacheAssetBundle (string url, int version, Action<float> progress, Action<string> fail, Action<WWW> finished, float timeout = 15f) {
//Debug.Log("loadAssetAndCache : " + url);
StartCoroutine(CoroutineDownloadAndCacheAssetBundle(url, version, progress, fail, finished, timeout));
}
IEnumerator CoroutineDownloadAndCacheAssetBundle (string url, int version, Action<float> progress, Action<string> fail, Action<WWW> finished, float timeout) {
// Wait for the Caching system to be ready
while (!Caching.ready)
yield return null;
// Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache
using (WWW www = WWW.LoadFromCacheOrDownload(System.Uri.EscapeUriString(url), version)) {
float startTime = Time.realtimeSinceStartup;
float lastProgress = 0;
//try to finish downloading file
while (!www.isDone) {
//notify callback if needed
if (progress != null)
progress(www.progress);
//if there is progress being made
if (lastProgress < www.progress) {
//take note
lastProgress = www.progress;
//reset timeout
startTime = Time.realtimeSinceStartup;
}
//if the download is taking too much time
if (Time.realtimeSinceStartup - startTime >= timeout) {
//do not download anymore
if (fail != null) {
fail("Request timed out");
}
yield break;
}
yield return waitWhenCheckProgress;
}
yield return www;
if (www.error != null) {
// throw new Exception("WWW download had an error:" + www.error);
if (fail != null)
fail(www.error);
}
else {
if (finished != null)
finished(www);
}
} // memory is freed from the web stream (www.Dispose() gets called implicitly)
}
public void DownloadAndCacheAsset (string url, int version, Action<float> progress, Action<string> fail, Action<WWW> finished, bool hideRealFileName = true, float timeout = 15f) {
StartCoroutine(CoroutineDownloadAndCacheAsset(url, version, progress, fail, finished, hideRealFileName, timeout));
}
IEnumerator CoroutineDownloadAndCacheAsset (string url, int version, Action<float> progress, Action<string> fail, Action<WWW> finished, bool hideRealFilename, float timeout) {
if (!isInitialized) { Initialize(); }
//this.Print("Receiving request for url " + url + " version: " + version);
string assetPath;
bool loadFromLocal = false;
//check if the asset has been downloaded before
if (db.assets.ContainsKey(url)) {
//if yes, check its version
int downloadedVersion = db.assets[url].version;
//this.Print("Asset already existed, with version: " + downloadedVersion);
//if the downloaded version is not the same as expected
if (downloadedVersion != version) {
//we need to re-download it
assetPath = url;
//and delete cached version
FileUtilities.DeleteFile(db.assets[url].localPath, true);
//this.Print("Removing old version");
//remove item from cache
db.assets.Remove(url);
}
else {
//if the url is requested again
//check if the asset is inaccessible or not
if (FileUtilities.IsFileExist(db.assets[url].localPath, true)) {
//if yes, load it from cache
assetPath = "file://" + db.assets[url].localPath;
loadFromLocal = true;
}
else {
//or else, try to reload it
assetPath = url;
db.assets.Remove(url);
// Debug.Log("Asset file is inaccessible, will try to download it again");
}
}
}
else {
//if the asset has never been downloaded before, download it
assetPath = url;
//this.Print("Asset not existed, trying to download from url");
}
//assetPath = "file://E:/gits/Amanotes/piano-challenge-2/DownloadedData\\-1225165794/CanonRock.txt";
//this.Print("Downloading asset from url: " + assetPath);
//download asset from suitable path
using (WWW www = new WWW(assetPath)) {
float startTime = Time.realtimeSinceStartup;
float lastProgress = 0;
//try to finish downloading file
while (!www.isDone) {
//notify callback if needed
if (progress != null)
progress(www.progress);
//print("Progress: " + www.progress);
//if there is progress being made
if (lastProgress < www.progress) {
//take note
lastProgress = www.progress;
//reset timeout
startTime = Time.realtimeSinceStartup;
}
//if the download is taking too much time
if (Time.realtimeSinceStartup - startTime >= timeout) {
//do not download anymore
if (fail != null) {
fail("Request timed out");
}
yield break;
}
yield return waitWhenCheckProgress;
}
yield return www;
//print("ProgressDone: " + www.progress);
if (www.error != null) {
this.Print("Download error: " + www.error);
if (fail != null)
fail(www.error);
}
else {
if (finished != null) {
//cache the file in local storage if is newly download from Internet
if (!loadFromLocal) {
string fileName = ExtractFileNameFromURL(assetPath);
string filePath;
if (hideRealFilename) {
filePath = assetPath.GetHashCode().ToString() + fileName.GetHashCode().ToString();
//Debug.Log(filepath);
}
else {
filePath = fileName;
}
filePath = filePath.Sanitize();
filePath = filePath.Replace("%", "");
string localPath = FileUtilities.SaveFile(www.bytes, filePath);
//analytic data in Parse
AnalyticsDownloadData(fileName);
DownloadedAssetItem item = new DownloadedAssetItem();
item.url = url;
item.version = version;
item.localPath = localPath;
item.dateCreated = DateTime.UtcNow;
if (db.assets.ContainsKey(url)) {
db.assets[url] = item;
}
else {
db.assets.Add(url, item);
}
//this.Print("Asset cached, file name: " + fileName);
//update db
FileUtilities.SerializeObjectToFile(db, DB_FILE, "tng2903");
}
//print("Download finished");
finished(www);
}
}
}
}
public void AnalyticsDownloadData(string fileName)
{
//var query = new ParseQuery<ParseObject>(PARSE_TABLE_ANALYTICS)
// .WhereEqualTo(PARSE_DATANAME_ROW, fileName);
//query.FindAsync().ContinueWith(
// t =>
// {
// IEnumerator<ParseObject> obj = t.Result.GetEnumerator();
// obj.MoveNext();
// if (obj.Current == null)
// {
// //Debug.Log("null");
// ParseObject analyticsData = new ParseObject(PARSE_TABLE_ANALYTICS);
// analyticsData[PARSE_DATANAME_ROW] = fileName;
// analyticsData[PARSE_COUNTERS_ROW] = 1;
// analyticsData.SaveAsync();
// }
// else
// {
// //Debug.Log("not null");
// obj.Current.Increment(PARSE_COUNTERS_ROW, 1);
// obj.Current.SaveAsync();
// }
// });
}
public void RemoveAsset (string url) {
if (db.assets.ContainsKey(url)) {
FileUtilities.DeleteFile(db.assets[url].localPath);
db.assets.Remove(url);
}
}
public void DownloadAsset (string url, Action<float> progress, Action<string> fail, Action<WWW> finished, float timeout = 15f) {
StartCoroutine(CoroutineDownloadAsset(url, progress, fail, finished, timeout));
}
IEnumerator CoroutineDownloadAsset (string url, Action<float> progress, Action<string> fail, Action<WWW> finished, float timeout) {
// Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache
using (WWW www = new WWW(url)) {
float startTime = Time.realtimeSinceStartup;
float lastProgress = 0;
//try to finish downloading file
while (!www.isDone) {
//notify callback if needed
if (progress != null)
progress(www.progress);
//if there is progress being made
if (lastProgress < www.progress) {
//take note
lastProgress = www.progress;
//reset timeout
startTime = Time.realtimeSinceStartup;
}
//if the download is taking too much time
if (Time.realtimeSinceStartup - startTime >= timeout) {
//do not download anymore
if (fail != null) {
fail("Request timed out");
}
yield break;
}
yield return waitWhenCheckProgress;
}
yield return www;
if (www.error != null) {
if (fail != null)
fail(www.error);
}
else {
if (finished != null)
finished(www);
}
} // memory is freed from the web stream (www.Dispose() gets called implicitly)
}
public void DeleteCachedAsset (string url, int version) {
StartCoroutine(CoroutineDeleteCachedAsset(url, version));
}
IEnumerator CoroutineDeleteCachedAsset (string url, int version) {
while (!Caching.ready)
yield return null;
uint a = 0;
using (WWW www = WWW.LoadFromCacheOrDownload(System.Uri.EscapeUriString(url), version, a)) {
yield return www;
if (www.error != null) {
Debug.LogWarning("Error in delete file : " + url + "\t Error: " + www.error);
}
else {
Debug.Log("Deleted : " + url);
}
}
}
public string ExtractFileNameFromURL (string url) {
if (string.IsNullOrEmpty(url)) { return string.Empty; }
return url.Substring(url.LastIndexOf('/'));
}
}
public class DownloadedAssetDatabase {
public Dictionary<string, DownloadedAssetItem> assets;
}
public class DownloadedAssetItem {
public string url;
public string localPath;
public int version;
public DateTime dateCreated;
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PaperPlane.API.ProtocolStack.Security.Auth
{
public class TLAuth
{
public TLAuth(byte[] key, long salt)
{
AuthKey = key;
Salt = salt;
}
public byte[] AuthKey { get; }
public long Salt { get; }
}
}
|
namespace TestDummies;
public class DummyWrappingSink : ILogEventSink
{
[ThreadStatic]
static List<LogEvent>? _emitted;
public static List<LogEvent> Emitted => _emitted ??= new();
readonly ILogEventSink _sink;
public DummyWrappingSink(ILogEventSink sink)
{
_sink = sink;
}
public void Emit(LogEvent logEvent)
{
Emitted.Add(logEvent);
_sink.Emit(logEvent);
}
public static void Reset()
{
_emitted = null;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace NSchedule.Entities
{
public class Group : Scheduleable
{
[JsonProperty("attDLs")]
public List<object> AttDLs { get; set; }
}
} |
using System;
using Framework.Core.Common;
using NUnit.Framework;
using Tests.Data.Van;
using Tests.Pages.Van.LogIn;
using Tests.Pages.Van.Main;
using Tests.Pages.Van.Main.Common.DefaultPage;
namespace Tests.Projects.Van.AFLMembershipTests
{
public class UserWith1082CanSeeAFLWorksiteAndEmployerOnCD
{
private Driver _driver;
private const String CLIENT_ID = "afl";
private VanTestUser userWith1082 = new VanTestUser
{
UserName = "mtta1082",
Password = "fluffhead66!",
PinCode = "1234",
ClientId = CLIENT_ID
};
[SetUp]
public void SetUp()
{
//start browser
_driver = new Driver();
}
/// <summary>
/// Ensures that with SF 1082 (Search and View Member Employers),
/// the test user can see restricted items on the ContactsDetails page
/// </summary>
[Test]
[Category("van"), Category("van_smoketest"), Category("van_afl")]
public void UserWith1082CanSeeAFLWorksiteAndEmployerOnCDTest()
{
var login = new LoginPage(_driver, CLIENT_ID);
var homePage = new VoterDefaultPage(_driver);
// log in to AFL VF MA with 1082
login.Login(userWith1082);
homePage.ClickMyVotersTab();
const string CONTACTS_DETAILS_PAGE = "ContactsDetails.aspx?VANID=EIDCE3DBQ";
//this is the only place with an already written 'go to this page directly' function
var contactsDetailsPage = new ContactDetailsPage(_driver);
contactsDetailsPage.GoToHTTPSContactsDetailsPageDirectlyAFLMembership(CONTACTS_DETAILS_PAGE);
Assert.IsTrue(_driver.FindTextInTable(contactsDetailsPage.MembershipPageSection, "Employer"));
Assert.IsTrue(_driver.FindTextInTable(contactsDetailsPage.MembershipPageSection, "Work Location"));
}
[TearDown]
public void TearDown()
{
_driver.BrowserQuit();
}
}
}
|
using System.ComponentModel.DataAnnotations;
using DataLayer.Entities;
namespace SolarSystemWeb.Models.Entities
{
public class SpaceObjectTypeDto : SimpleModel
{
public SpaceObjectTypeDto ()
{
Plural = "";
}
[Required(ErrorMessage = "Нужно указать форму множественного числа")]
public string Plural { get; set; }
public bool IsSun
{
get { return Plural == null; }
}
}
} |
using HPYL.BLL;
using HPYL.Model;
using HPYL_API.App_Start.Attribute;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using XL.Application.Code;
using XL.Model.Message;
namespace HPYL_API.Controllers.FollowType
{
/// <summary>
/// 诊所项目类
/// </summary>
[TokenAttribute] //针对当前类验证签名
public class FollowTypeController : ApiController
{
private FollowPlanBLL FBLL = new FollowPlanBLL();//诊疗科目
#region 获取数据
/// <summary>
/// 获取诊疗项目一级分类+二级用户分类
/// </summary>
/// <param name="ClinicId">诊所ID</param>
/// <param name="UID">当前登录用户ID</param>
/// <returns></returns>
[HttpGet]
public CallBackResult FollowTypeJoinList(long ClinicId, long UID)
{
CallBackResult apiResult = new CallBackResult();
try
{
List<GetFollowType> TypeList = new List<GetFollowType>();
List<SecondList> SecondList = new List<SecondList>();
//获取一级分类
var data = FBLL.FollowTypeList(ClinicId);
foreach (DataRow item in data.Rows)
{
GetFollowType cmo = new GetFollowType();
cmo.HFT_ID = item["HFT_ID"].ToString();
cmo.HFT_Name = item["HFT_Name"].ToString();
//获取二级分类
var datasecond = FBLL.FollowTypeSecondList(ClinicId, UID, long.Parse(item["HFT_ID"].ToString()));
foreach (DataRow sitem in datasecond.Rows)
{
SecondList cms = new SecondList();
cms.HFT_ID = sitem["HFT_ID"].ToString();
cms.HFT_Name = sitem["HFT_Name"].ToString();
SecondList.Add(cms);
}
cmo.SecondList = SecondList;
TypeList.Add(cmo);
}
apiResult.Data = TypeList;
apiResult.Result = 1;
apiResult.Message = "加载成功";
}
catch (Exception ex)
{
apiResult.Result = 0;
apiResult.Message = "加载失败";
new CCBException("获取诊疗项目一级分类+二级用户分类:", ex);
}
return apiResult;
}
/// <summary>
/// 获取诊疗项目一级分类(ClinicId 诊所ID)
/// </summary>
/// <param name="ClinicId">诊所ID</param>
/// <returns></returns>
[HttpGet]
public CallBackResult FollowTypeList(long ClinicId)
{
CallBackResult apiResult = new CallBackResult();
try
{
List<BaseFollowType> TypeList = new List<BaseFollowType>();
var data = FBLL.FollowTypeList(ClinicId);
foreach (DataRow item in data.Rows)
{
BaseFollowType cmo = new BaseFollowType();
cmo.HFT_ID = item["HFT_ID"].ToString();
cmo.HFT_Name = item["HFT_Name"].ToString();
TypeList.Add(cmo);
}
apiResult.Data = TypeList;
apiResult.Result = 1;
apiResult.Message = "加载成功";
}
catch (Exception ex)
{
apiResult.Result = 0;
apiResult.Message = "加载失败";
new CCBException("获取诊疗项目分类:", ex);
}
return apiResult;
}
/// <summary>
/// 获取诊疗项目2级分类
/// </summary>
/// <param name="ClinicId">诊所ID</param>
/// <param name="UID">当前登录用户ID</param>
/// <param name="ParentId">父类ID</param>
/// <returns></returns>
[HttpGet]
public CallBackResult FollowTypeSecondList(long ClinicId, long UID, long ParentId)
{
CallBackResult apiResult = new CallBackResult();
try
{
List<BaseFollowType> TypeList = new List<BaseFollowType>();
var data = FBLL.FollowTypeSecondList(ClinicId, UID, ParentId);
foreach (DataRow item in data.Rows)
{
BaseFollowType cmo = new BaseFollowType();
cmo.HFT_ID = item["HFT_ID"].ToString();
cmo.HFT_Name = item["HFT_Name"].ToString();
TypeList.Add(cmo);
}
apiResult.Data = TypeList;
apiResult.Result = 1;
apiResult.Message = "加载成功";
}
catch (Exception ex)
{
apiResult.Result = 0;
apiResult.Message = "加载失败";
new CCBException("获取诊疗项目2级分类:", ex);
}
return apiResult;
}
#endregion
#region 提交数据
/// <summary>
/// 添加诊疗项目
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
[HttpPost]
[ValidateModel]
public CallBackResult InFollowProject(ProjectPost info)
{
CallBackResult apiResult = new CallBackResult();
try
{
if (FBLL.AddProject(info))
{
apiResult.Result = 1;
apiResult.Message = "已成功添加诊疗项目";
}
else
{
apiResult.Result = 0;
apiResult.Message = "诊疗项目添加失败";
}
}
catch (Exception ex)
{
apiResult.Result = 0;
apiResult.Message = "诊疗项目添加失败";
new CCBException(" 添加诊疗项目", ex);
}
return apiResult;
}
#endregion
}
} |
// File Prologue
// Name: Darren Moody
// CS 1400 Section 005
// Assignment: Project 10
// Date: 12/06/2013
//
//
//
// I declare that the following code was written by me or provided
// by the instructor for this project. I understand that copying source
// code from any other source constitutes cheating, and that I will receive
// a zero on this project if I am found in violation of this policy.
// ---------------------------------------------------------------------------
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace project10
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Wind Chill Calculator");
Console.WriteLine("Darren Moody");
Console.WriteLine("CS1400 - Project 10");
Console.WriteLine("--------------------------------------------------------\n\n");
string filePath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
Console.Write("Enter a file name in your Documents folder: ");
string fileName = Console.ReadLine();
string pathPointer = filePath + fileName;
Console.WriteLine("Opening the file\n\n\n");
StreamReader theTextFile = new StreamReader(pathPointer);
double tempFarenheit = 0.0, windSpeed = 0.0, windChill = 0.0;
string inputstring;
while ((inputstring = theTextFile.ReadLine()) != null)
{
try // first time I've used try and catch, Dr. Stanley taught us this Tuesday
{
string[] vals = inputstring.Split(' ');
tempFarenheit = double.Parse(vals[0]);
windSpeed = double.Parse(vals[1]);
windChill = CalcWindChill(tempFarenheit, windSpeed);
Console.WriteLine("For a temperature in degree F of {0:f2}", tempFarenheit);
Console.WriteLine("and a wind velocity in mph of {0:f2}", windSpeed);
Console.WriteLine("The wind chill factor is {0:f2} degrees\n", windChill);
}
catch
{
Console.WriteLine("Error, Data Unrecognized...");
}
}
Console.ReadLine();
}
// The CalcWindChill method
// Purpose: calculates the wind chill in degrees Far.
// Parameters: 2 doubles, temperature in F and wind speed
// Returns: double calculated wind chill
static double CalcWindChill(double tempFar, double windSpeed)
{
// W = 35.74 + 0.6215t - 35.75 (v0.16) + 0.4275t(v0.16)
const double WC_NUM1 = 35.74, WC_NUM2 = 0.6215, WC_NUM3 = 35.75, WC_NUM4 = 0.4275, EXPONENT = 0.16;
double windChill = WC_NUM1 + WC_NUM2 * tempFar - WC_NUM3 * Math.Pow(windSpeed, EXPONENT) +
WC_NUM4 * tempFar * Math.Pow(windSpeed, EXPONENT);
return windChill;
}
}
}
|
using System;
using System.Linq;
using System.Web.Mvc;
using Lecture04.BlogPosts.AspNetMvc.Controllers.ViewModels;
using Lecture04.BlogPosts.AspNetMvc.Repository;
using Lecture04.BlogPosts.EntityFramework.Contexts;
using Lecture04.BlogPosts.EntityFramework.Domain;
using Lecture04.BlogPosts.EntityFramework.Repositories;
namespace Lecture04.BlogPosts.AspNetMvc.Controllers
{
public class HomeController : Controller
{
private readonly IBlogPostRepository repository;
public HomeController()
{
var connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
var context = new LocalDatabaseContext(connectionString);
repository = new DatabaseBlogPostRepository(context);
}
[HttpGet]
public ActionResult Index()
{
var model = new BlogPostViewModel
{
TopBlogPosts = Enumerable.Empty<BlogPost>(),
BlogPosts = repository.GetBlogPosts()
};
return View("Index", model);
}
[HttpGet]
public ActionResult About()
{
return View("About");
}
}
} |
namespace _01._OddLines
{
using System;
using System.IO;
public class Startup
{
public static void Main()
{
StreamReader reader = new StreamReader("file.txt");
using (reader)
{
string input = reader.ReadLine();
int count = 0;
while (input != null)
{
if (count % 2 != 0)
{
Console.WriteLine(input);
}
count++;
input = reader.ReadLine();
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExitGames.Logging;
using ExitGames.Logging.Log4Net;
using log4net.Config;
using Photon.SocketServer;
namespace ThreeCountriesKillServer
{
/// <summary>
/// 所有的Photon Server的服务端的主类(程序入口)都要继承自Photon.SocketServer.ApplicationBase
/// </summary>
public class ThreeCountriesKillServer : ApplicationBase
{
public static readonly ILogger log = LogManager.GetCurrentClassLogger();//声明日志
/// <summary>
/// 连接请求,每当有客户端连接时调用,创建一个对应的客户端连接对象PeerBase
/// </summary>
/// <param name="initRequest"></param>
/// <returns></returns>
protected override PeerBase CreatePeer(InitRequest initRequest)
{
log.Info("客户端连接");//日志输出
return new ClientPeer(initRequest);
}
/// <summary>
/// 启动时调用
/// </summary>
protected override void Setup()
{
//日志初始化
log4net.GlobalContext.Properties["Photon:ApplicationLogPath"] = Path.Combine(Path.Combine(ApplicationRootPath, "bin_Win64"), "log");//设置日志输出路径
FileInfo logFileInfo = new FileInfo(Path.Combine(BinaryPath, "log4net.config"));
if (logFileInfo.Exists)
{
LogManager.SetLoggerFactory(Log4NetLoggerFactory.Instance);//设置使用哪个log4net日志插件
XmlConfigurator.ConfigureAndWatch(logFileInfo);//让log4net插件读取photon的配置文件
}
log.Info("服务端启动");//日志输出
}
/// <summary>
/// 关闭时调用
/// </summary>
protected override void TearDown()
{
log.Info("服务端关闭");//日志输出
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/**
* @author Chris Foulston
*/
namespace Malee.Hive.Util.IK {
public class IKHuman : IKArmature {
public GameObject Hips;
public GameObject Spine;
public GameObject Neck;
public GameObject Head;
public GameObject Chest;
public GameObject LeftShoulder;
public GameObject LeftUpperArm;
public GameObject LeftLowerArm;
public GameObject LeftHand;
public GameObject RightShoulder;
public GameObject RightUpperArm;
public GameObject RightLowerArm;
public GameObject RightHand;
public GameObject LeftUpperLeg;
public GameObject LeftLowerLeg;
public GameObject LeftFoot;
public GameObject LeftToes;
public GameObject RightUpperLeg;
public GameObject RightLowerLeg;
public GameObject RightFoot;
public GameObject RightToes;
public IKHuman(Transform transform)
: this(transform, IKType.Inverse) {
}
public IKHuman(Transform transform, IKType type)
: base(transform, type) {
}
public Dictionary<GameObject, IKJoint> joints {
get;
private set;
}
public void Build() {
Build(type);
}
public void Build(IKType type) {
joints = new Dictionary<GameObject, IKJoint>();
if (Hips == null) {
throw new UnityException("Hips must be defined");
}
else if (Neck == null) {
throw new UnityException("Neck must be defined");
}
CreateStructure(type, Hips, Spine, Chest, Neck, Head);
CreateStructure(type, Neck, LeftShoulder, LeftUpperArm, LeftLowerArm, LeftHand);
CreateStructure(type, Neck, RightShoulder, RightUpperArm, RightLowerArm, RightHand);
CreateStructure(type, Hips, LeftUpperLeg, LeftLowerLeg, LeftFoot, LeftToes);
CreateStructure(type, Hips, RightUpperLeg, RightLowerLeg, RightFoot, RightToes);
}
public void BreakHierarchy(Transform root) {
foreach (IKJoint joint in joints.Values) {
joint.transform.parent = root;
}
}
public IKJoint GetJointFromGameObject(GameObject parent) {
IKJoint joint;
if (joints.TryGetValue(parent, out joint)) {
return joint;
}
return null;
}
public void CreateStructure(IKType type, params GameObject[] list) {
if (list.Length > 0) {
int i, len = list.Length;
IKJoint parent = CreateJointFromGameObject(list[0], type);
for (i = 1; i < len; i++) {
IKJoint joint = GetJointFromGameObject(list[i]);
if (joint != null) {
parent.AddChild(joint);
parent = joint;
}
else {
joint = CreateJointFromGameObject(list[i], type);
if (joint != null) {
parent.AddChild(joint);
parent = joint;
}
}
}
}
}
public IKJoint CreateJointFromGameObject(GameObject gameObject, IKType type) {
if (!joints.ContainsKey(gameObject)) {
return joints[gameObject] = new IKJoint(gameObject.transform, type);
}
else {
return joints[gameObject];
}
}
}
}
|
using AutoMapper;
using BLL.Dto;
using BLL.Exceptions;
using BLL.Interfaces;
using DAL.Entities;
using DAL.Interfaces;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BLL.Services
{
public class CategoryService : ICategoryService
{
readonly IUnitOfWork _dataBase;
private readonly UserManager<AppUser> _userManager;
readonly IMapper _mapper;
public CategoryService(IUnitOfWork unitOfWork, UserManager<AppUser> userManager, IMapper mapper)
{
_dataBase = unitOfWork;
_userManager = userManager;
_mapper = mapper;
}
public async Task AddCategoryAsync(CategoryDto category)
{
category.Id = 0;
if (String.IsNullOrEmpty(category.Name))
throw new ModelException("category name should not be empty");
//TODO: Add check for non-existing user
var categoryEntity = _mapper.Map<CategoryDto, Category>(category);
await _dataBase.CategoryRepository.AddAsync(categoryEntity);
await _dataBase.SaveAsync();
}
public async Task DeleteCategoryAsync(int categoryId, string userId)
{
var category = await _dataBase.CategoryRepository.GetByIdAsync(categoryId);
if (category == null || category.AppUserId != userId)
throw new ModelException("no such category Id created by the user");
await _dataBase.CategoryRepository.DeleteByIdAsync(categoryId);
await _dataBase.SaveAsync();
}
public IEnumerable<CategoryDto> GetCategories(string userId)
{
var categoryEntities = _dataBase.CategoryRepository.FindAll().Where(c => c.AppUserId == userId).AsEnumerable();
return _mapper.Map<IEnumerable<Category>, IEnumerable<CategoryDto>>(categoryEntities);
}
public async Task RenameCategoryAsync(int categoryId, string userId, string newName)
{
var category = await _dataBase.CategoryRepository.GetByIdAsync(categoryId);
if (category == null || category.AppUserId != userId)
throw new ModelException("no such category Id created by the user");
if (String.IsNullOrEmpty(newName))
throw new ModelException("category name should not be empty");
category.Name = newName;
_dataBase.CategoryRepository.Update(category);
await _dataBase.SaveAsync();
}
}
}
|
using System.Collections.Generic;
using System.Windows;
using CaveDwellers.Core;
using CaveDwellers.Positionables;
using CaveDwellers.Positionables.Monsters;
using CaveDwellers.Utility;
using CaveDwellersTest.MonstersForTest;
using CaveDwellersTest.StonesForTest;
namespace CaveDwellersTest.LevelsForTest
{
public class TenByTenLevel
{
private readonly WorldMatrix _world = new WorldMatrix();
public TenByTenLevel()
{
for (var x = 0; x < 10; x++)
{
_world.Add(x, 0, CreateStone());
_world.Add(x, 9, CreateStone());
}
for (var y = 1; y < 9; y++)
{
_world.Add(0, y, CreateStone());
_world.Add(9, y, CreateStone());
}
_world.Add(3, 3, CreateMonster());
_world.Add(3, 7, CreateMonster());
_world.Add(7, 3, CreateMonster());
_world.Add(7, 7, CreateMonster());
}
private Monster CreateMonster()
{
return new Monster1x1(_world, new Rnd(200, 200));
}
private static Stone CreateStone()
{
return new Stone1x1();
}
public IEnumerable<KeyValuePair<IPositionable, Point>> GetObjects()
{
return _world.GetObjects();
}
}
} |
using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace iPadPos
{
public class WebService
{
static WebService main;
public static WebService Main {
get {
return main ?? (main = new WebService ());
}
set {
main = value;
}
}
public WebService ()
{
}
public async Task SyncAll ()
{
coupons.Clear ();
newProducts.Clear ();
await GetTaxTypes ();
await GetTransactions ();
await GetPaymentTypes ();
await GetCoupons ();
await GetNewProducts ();
}
public async Task<bool> SignIn(string id)
{
var client = CreateClient ();
var respons = await client.GetAsync (Path.Combine ("SignIn", id));
var success = bool.Parse (await respons.Content.ReadAsStringAsync ());
return success;
}
public async Task<List<Customer>> SearchCustomer (string cust)
{
return await GetGenericList<Customer> (string.Format ("CustomerSearch/{0}", cust));
}
public async Task<bool> SaveWorkingInvoice(Invoice invoice)
{
try{
invoice.RegisterId = Settings.Shared.RegisterId.ToString();
var client = CreateClient ();
var json = Newtonsoft.Json.JsonConvert.SerializeObject (invoice);
var respons = await client.PostAsync ("WorkingInvoice", new StringContent (json, Encoding.UTF8, "application/json"));
var success = !string.IsNullOrEmpty(await respons.Content.ReadAsStringAsync ());
return success;
}
catch(Exception ex) {
Console.WriteLine (ex);
}
return false;
}
public async Task<bool> DeleteWorkingInvoice(Invoice invoice)
{
var client = CreateClient ();
var json = Newtonsoft.Json.JsonConvert.SerializeObject (invoice);
var respons = await client.DeleteAsync (Path.Combine("WorkingInvoice",invoice.RecordId.ToString()));
var success = !string.IsNullOrEmpty(await respons.Content.ReadAsStringAsync ());
return success;
}
public async Task<bool> Test()
{
try{
var success = await GetUrl ("Test");
return bool.Parse(success);
}
catch(Exception ex) {
Console.WriteLine (ex);
return false;
}
}
public async Task<Item> GetItem (string id)
{
return await Get<Item> ("items", id);
}
public async Task<Customer> GetCustomer (string id)
{
return await Get<Customer> ("customer", id);
}
public async Task<List<TaxType>> GetTaxTypes ()
{
return await GetGenericList<TaxType> ("TaxType", true);
}
public async Task<List<PaymentType>> GetPaymentTypes ()
{
return await GetGenericList<PaymentType> ("PaymentType", true);
}
public async Task<List<TransactionType>> GetTransactions ()
{
return await GetGenericList<TransactionType> ("TransactionType", true);
}
public async Task<List<Item>> GetNewCustomerInformation()
{
var items = (await GetGenericList<Item> ("NewCustomerTracking"));
items.ForEach (x => x.ItemType = ItemType.NewCustomerTracking);
return items;
}
List<Item> newProducts = new List<Item>();
public async Task<List<Item>> GetNewProducts()
{
if(newProducts.Count > 0)
return newProducts;
var items = (await GetGenericList<Item> ("NewProducts"));
items.ForEach (x => x.ItemType = ItemType.NewProduct);
newProducts = items;
NotificationCenter.Shared.ProcNewProductChanged ();
return newProducts;
}
public async Task<string> GetNextPostedInvoiceId()
{
return (await GetUrl (string.Format("NextInvoiceId/{0}", Settings.Shared.RegisterId))).Trim('"');
}
public Task<Invoice> GetInvoice(string id)
{
return Get<Invoice> ("WorkingInvoice", id);
}
public Task<List<Invoice>> GetInvoices()
{
return Get<List<Invoice>> ("InvoiceSearch");
}
List<Item> coupons = new List<Item>();
public async Task<List<Item>> GetGroupedCoupons(int section)
{
var c = await GetCoupons ();
return c.GroupBy (x => x.UseAlterate ()).ElementAt(section).ToList();
}
public async Task<List<Item>> GetCoupons()
{
if (coupons.Count > 0)
return coupons;
var items = (await GetGenericList<Coupon> ("Coupons")).Where(x=> x.IsValidToday);
NotificationCenter.Shared.ProcCouponsChanged ();
coupons = items.Cast<Item>().ToList();
return coupons;
}
public async Task<List<BuyInvoice>> GetUnpostedBuys()
{
var items = await GetGenericList<BuyInvoice> ("PayoutBuy");
return items;
}
public async Task<bool> PostInvoice (Invoice invoice)
{
var stringResult = "";
try{
invoice.RegisterId = Settings.Shared.RegisterId.ToString();
var client = CreateClient ();
var json = Newtonsoft.Json.JsonConvert.SerializeObject (invoice);
var respons = await client.PostAsync ("Invoice", new StringContent (json, Encoding.UTF8, "application/json"));
stringResult = await respons.Content.ReadAsStringAsync ();
var result = Deserialize<PostedInvoiceResult>(stringResult);
if(result.Success)
Settings.Shared.LastPostedInvoice = result.InvoiceId;
return result.Success;
}
catch(Exception ex) {
Console.WriteLine (ex);
Console.WriteLine (stringResult);
}
return false;
}
public async Task<bool> PrintInvoice(string invoiceId)
{
try{
var success = await GetUrl (string.Format("PrintInvoice/{0}", invoiceId));
return bool.Parse(success);
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
return false;
}
public async Task<Customer> CreateCustomer (Customer customer)
{
try {
var client = CreateClient ();
var json = Newtonsoft.Json.JsonConvert.SerializeObject (customer);
var respons = await client.PostAsync ("Customer", new StringContent (json, Encoding.UTF8, "application/json"));
var custJson = await respons.Content.ReadAsStringAsync ();
return Deserialize<Customer>(custJson) ;
} catch (Exception ex) {
Console.WriteLine (ex);
}
return customer;
}
public async Task<bool> UpdateCustomer (Customer customer)
{
try {
var client = CreateClient ();
var json = Newtonsoft.Json.JsonConvert.SerializeObject (customer);
var respons = await client.PutAsync ("Customer", new StringContent (json, Encoding.UTF8, "application/json"));
var responseString = await respons.Content.ReadAsStringAsync ();
var success = bool.Parse (responseString);
return success;
} catch (Exception ex) {
Console.WriteLine (ex);
}
return false;
}
public async Task<List<T>> GetGenericList<T> (string path, bool insert = false)
{
var items = await Get<List<T>> (path);
if (insert) {
Database.Main.InsertAll (items, "OR REPLACE");
}
return items;
}
public Task<Stream> GetUrlStream (string path)
{
var client = CreateClient ();
return client.GetStreamAsync (path);
}
public Task<string> GetUrl (string path)
{
var client = CreateClient ();
return client.GetStringAsync (path);
}
HttpClient CreateClient ()
{
var client = new HttpClient ();
client.BaseAddress = new Uri (Settings.Shared.CurrentServerUrl);
return client;
}
public async Task<T> Get<T> (string path, string id = "")
{
try {
Console.WriteLine (path);
var data = await GetUrl (Path.Combine (path, id));
Console.WriteLine (data);
return await Task.Factory.StartNew (() => {
return Deserialize<T> (data);
});
} catch (Exception ex) {
Console.WriteLine (ex);
return default(T);
}
}
T Deserialize<T> (string data)
{
try {
return Newtonsoft.Json.JsonConvert.DeserializeObject<T> (data);
} catch (Exception ex) {
Console.WriteLine (ex);
}
return default(T);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
public class npcTalkManager : MonoBehaviour
{
public GameObject UItextBox;
public Text dialogueText;
public bool updateBox;
/*
NAME: Start
SYNOPSIS:
Start is called before the first frame update
DESCRIPTION:
Start is called before the first frame update
RETURNS:
AUTHOR:
Thomas Furletti
DATE:
07/08/2020
*/
void Start()
{
}
/*
NAME: Update
SYNOPSIS:
Gets the keyboard entry with the space button to open the npc to chracter dialog.
DESCRIPTION:
This function holds the ui features to start talking dialogs with npc to character
interations with the space bar as the activator.
RETURNS:
AUTHOR:
Thomas Furletti
DATE:
07/08/2020
*/
void Update()
{
if(UItextBox.activeInHierarchy == true && Input.GetButtonDown("space")) {
UItextBox.SetActive(false);
}
else if ((updateBox && Input.GetButtonDown("space"))) {
UItextBox.SetActive(true);
}
}
/*
NAME: OpenBox
SYNOPSIS:
Opens the UI box and enters the text that will go inside it when npc to player
interations.
DESCRIPTION:
This function opens the text box that the player will see in the ui and fills it
with text. It does this by setting the UI objects that are already create active.
RETURNS:
AUTHOR:
Thomas Furletti
DATE:
07/08/2020
*/
public void OpenBox(string inputText) {
updateBox = true;
UItextBox.SetActive(true);
dialogueText.text = inputText;
}
}
|
namespace RosPurcell.Web.Infrastructure.Mapping
{
using Umbraco.Core.Models;
using Zone.UmbracoMapper;
public abstract class BaseMapping
{
/// <summary>
/// Maps the content to a model of the given type
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="mapper">Umbraco mapper</param>
/// <param name="content">Content to map from</param>
/// <returns>The model</returns>
protected static T Map<T>(IUmbracoMapper mapper, IPublishedContent content) where T : class, new()
{
var model = new T();
if (content == null)
{
return model;
}
mapper.Map(content, model);
return model;
}
}
}
|
using UnityEngine;
namespace Assets.Scripts
{
/// <summary>
/// Generic singleton instance to create manager
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class SingletonInstance<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
/// <summary>
/// Gets a generic instance
/// </summary>
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
}
return _instance;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServerLibrary
{
public class MessageReader
{
public static Dictionary<string, string> messages = new Dictionary<string, string>();
public MessageReader()
{
messages.Clear();
string line;
StreamReader file = new StreamReader("Messages.conf");
while ((line = file.ReadLine()) != null)
{
var cred = line.Split('=');
messages.Add(cred[0], cred[1]);
}
}
public string getMessage(string key)
{
return messages.FirstOrDefault(x => x.Key == key).Value;
}
}
} |
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.UnifiedPlatform.Service.Common.Models;
namespace Microsoft.UnifiedPlatform.Service.Common.Redis
{
public interface IRedisListProvider
{
Task<List<string>> GetAllLogs(ClusterConfigurationDto clusterConfiguration, AppConfigurationDto applicationConfiguration, bool commitLog);
}
}
|
using gView.Core.Framework.Exceptions;
using gView.Framework.system;
using gView.MapServer;
using gView.Server.AppCode;
using gView.Server.AppCode.Extensions;
using gView.Server.Models;
using gView.Server.Services.Logging;
using gView.Server.Services.MapServer;
using gView.Server.Services.Security;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace gView.Server.Controllers
{
public class ManageController : BaseController
{
private readonly MapServiceManager _mapServiceMananger;
private readonly MapServiceDeploymentManager _mapServiceDeploymentManager;
private readonly LoginManager _loginManager;
private readonly MapServicesEventLogger _logger;
public ManageController(MapServiceManager mapServiceManager,
MapServiceDeploymentManager mapServiceDeploymentManager,
LoginManager loginManager,
MapServicesEventLogger logger,
EncryptionCertificateService encryptionCertificateService)
: base(mapServiceManager, loginManager, encryptionCertificateService)
{
_mapServiceMananger = mapServiceManager;
_mapServiceDeploymentManager = mapServiceDeploymentManager;
_loginManager = loginManager;
_logger = logger;
}
public IActionResult Index()
{
try
{
var authToken = _loginManager.GetAuthToken(this.Request);
if (!authToken.IsManageUser)
{
return RedirectToAction("Login");
}
ViewData["mainMenuItems"] = "mainMenuItemsPartial";
return View();
}
catch (Exception)
{
return RedirectToAction("Login");
}
}
#region Login
[HttpGet]
public IActionResult Login()
{
if (Globals.AllowFormsLogin == false)
{
return RedirectToAction("Index", "Home");
}
return View(new ManageLoginModel());
}
[HttpPost]
public IActionResult Login(ManageLoginModel model)
{
try
{
if (Globals.AllowFormsLogin == false)
{
return RedirectToAction("Index", "Home");
}
//Console.WriteLine("UN: "+model.Username);
//Console.WriteLine("PW: "+model.Password);
if (String.IsNullOrWhiteSpace(model.Username))
{
throw new Exception("Username is required...");
}
if (String.IsNullOrWhiteSpace(model.Password))
{
throw new Exception("Password is required...");
}
var authToken = _loginManager.GetManagerAuthToken(model.Username.Trim(), model.Password.Trim(), createIfFirst: true);
if (authToken == null)
{
throw new Exception("Unknown user or password");
}
base.SetAuthCookie(authToken);
return RedirectToAction("Index");
}
catch (Exception ex)
{
model.ErrorMessage = ex.Message;
ex.ToConsole();
return View(model);
}
}
#endregion
public IActionResult Collect()
{
var mem1 = GC.GetTotalMemory(false) / 1024.0 / 1024.0;
GC.Collect();
var mem2 = GC.GetTotalMemory(true) / 1024.0 / 1024.0;
return Json(new { succeeded = true, mem1 = mem1, mem2 = mem2 });
}
#region Services
async public Task<IActionResult> Folders()
{
return await SecureApiCall(async () =>
{
var folderServices = _mapServiceMananger.MapServices
.Where(s => s.Type == MapServiceType.Folder)
.Select(s => s)
.OrderBy(s => s.Name)
.Distinct();
List<object> mapServiceJson = new List<object>();
foreach (var folderService in folderServices)
{
mapServiceJson.Add(await MapService2Json(folderService, await folderService.GetSettingsAsync()));
}
return Json(new
{
success = true,
folders = mapServiceJson.ToArray()
});
});
}
async public Task<IActionResult> Services(string folder)
{
folder = folder ?? String.Empty;
_mapServiceMananger.ReloadServices(folder, true);
return await SecureApiCall(async () =>
{
var servicesInFolder = _mapServiceMananger.MapServices
.Where(s => s.Type != MapServiceType.Folder &&
s.Folder == folder);
List<object> mapServiceJson = new List<object>();
foreach (var serviceInFolder in servicesInFolder)
{
mapServiceJson.Add(await MapService2Json(serviceInFolder, await serviceInFolder.GetSettingsAsync()));
}
return Json(new
{
success = true,
services = mapServiceJson.ToArray()
});
});
}
async public Task<IActionResult> SetServiceStatus(string service, string status)
{
return await SecureApiCall(async () =>
{
var mapService = _mapServiceMananger.MapServices.Where(s => s.Fullname == service).FirstOrDefault();
if (mapService == null)
{
throw new MapServerException("Unknown service: " + service);
}
var settings = await mapService.GetSettingsAsync();
switch (status.ToLower())
{
case "running":
if (!settings.IsRunning() || !_mapServiceMananger.Instance.IsLoaded(mapService.Name, mapService.Folder))
{
// start
settings.RefreshService = DateTime.UtcNow;
settings.Status = MapServiceStatus.Running;
await mapService.SaveSettingsAsync();
// reload
await _mapServiceMananger.Instance.GetServiceMapAsync(service.ServiceName(), service.FolderName());
}
break;
case "stopped":
settings.Status = MapServiceStatus.Stopped;
_mapServiceDeploymentManager.MapDocument.RemoveMap(mapService.Fullname);
await mapService.SaveSettingsAsync();
break;
case "refresh":
// stop
_mapServiceDeploymentManager.MapDocument.RemoveMap(mapService.Fullname);
// start
settings.RefreshService = DateTime.UtcNow;
settings.Status = MapServiceStatus.Running;
await mapService.SaveSettingsAsync();
// reload
await _mapServiceMananger.Instance.GetServiceMapAsync(service.ServiceName(), service.FolderName());
break;
}
return Json(new
{
success = true,
service = await MapService2Json(mapService, settings)
});
});
}
public IActionResult ServiceErrorLogs(string service, string last = "0")
{
return SecureApiCall(() =>
{
var errorsResult = _logger.ErrorLogs(service, Framework.system.loggingMethod.error, long.Parse(last));
return Json(new
{
errors = errorsResult.errors,
ticks = errorsResult.ticks > 0 ? errorsResult.ticks.ToString() : null
});
});
}
[HttpGet]
async public Task<IActionResult> ServiceSecurity(string service)
{
return await SecureApiCall(async () =>
{
service = service?.ToLower() ?? String.Empty;
var mapService = _mapServiceMananger.MapServices.Where(s => s.Fullname?.ToLower() == service).FirstOrDefault();
if (mapService == null)
{
throw new MapServerException("Unknown service: " + service);
}
var settings = await mapService.GetSettingsAsync();
List<string> allTypes = new List<string>(Enum.GetNames(typeof(AccessTypes)).Select(n => n.ToLower()).Where(n => n != "none"));
allTypes.Add("_all");
var accessRules = settings.AccessRules;
foreach (var interpreterType in _mapServiceMananger.Interpreters)
{
allTypes.Add("_" + ((IServiceRequestInterpreter)Activator.CreateInstance(interpreterType)).IdentityName.ToLower());
}
return Json(new
{
allTypes = allTypes.ToArray(),
accessRules = accessRules,
allUsers = _loginManager.GetManageAndTokenUsernames(),
anonymousUsername = Identity.AnonyomousUsername
});
});
}
[HttpPost]
async public Task<IActionResult> ServiceSecurity()
{
return await SecureApiCall(async () =>
{
var service = Request.Query["service"].ToString().ToLower();
var mapService = _mapServiceMananger.MapServices.Where(s => s.Fullname?.ToLower() == service).FirstOrDefault();
if (mapService == null)
{
throw new MapServerException("Unknown service: " + service);
}
var settings = await mapService.GetSettingsAsync();
settings.AccessRules = null; // Remove all
if (Request.Form != null)
{
var form = Request.Form;
foreach (var key in form.Keys)
{
if (key.Contains("~")) // username~accesstype or username~_interpreter
{
var username = key.Substring(0, key.IndexOf("~"));
var accessRule = settings.AccessRules?.Where(a => a.Username.ToLower() == username.ToLower()).FirstOrDefault();
if (accessRule == null)
{
accessRule = new MapServiceSettings.MapServiceAccess();
var rules = new List<IMapServiceAccess>();
if (settings.AccessRules != null)
{
rules.AddRange(settings.AccessRules);
}
rules.Add(accessRule);
settings.AccessRules = rules.ToArray();
}
accessRule.Username = username;
var rule = key.Substring(key.IndexOf("~") + 1, key.Length - key.IndexOf("~") - 1);
string serviceType = String.Empty;
if (rule == "_all")
{
serviceType = rule;
}
else if (rule.StartsWith("_") && _mapServiceMananger.Interpreters
.Select(t => new Framework.system.PlugInManager().CreateInstance<IServiceRequestInterpreter>(t))
.Where(i => "_" + i.IdentityName.ToLower() == rule.ToLower())
.Count() == 1) // Interpreter
{
serviceType = rule.ToLower();
}
else if (Enum.TryParse<AccessTypes>(rule, true, out AccessTypes accessType))
{
serviceType = accessType.ToString();
}
if (!String.IsNullOrWhiteSpace(serviceType))
{
if (Convert.ToBoolean(form[key]) == true)
{
accessRule.AddServiceType(serviceType);
}
else
{
accessRule.RemoveServiceType(serviceType);
}
}
}
}
}
await mapService.SaveSettingsAsync();
return Json(new
{
success = true,
service = await MapService2Json(mapService, settings)
});
});
}
[HttpGet]
async public Task<IActionResult> FolderSecurity(string folder)
{
return await SecureApiCall(async () =>
{
folder = folder?.ToLower() ?? String.Empty;
var mapService = _mapServiceMananger.MapServices.Where(s => s.Type == MapServiceType.Folder && s.Fullname?.ToLower() == folder).FirstOrDefault();
if (mapService == null)
{
throw new MapServerException("Unknown folder: " + folder);
}
var settings = await mapService.GetSettingsAsync();
List<string> allTypes = new List<string>(Enum.GetNames(typeof(FolderAccessTypes)).Select(n => n.ToLower()).Where(n => n != "none"));
allTypes.Add("_all");
var accessRules = settings.AccessRules;
foreach (var interpreterType in _mapServiceMananger.Interpreters)
{
allTypes.Add("_" + ((IServiceRequestInterpreter)Activator.CreateInstance(interpreterType)).IdentityName.ToLower());
}
return Json(new
{
allTypes = allTypes.ToArray(),
accessRules = accessRules,
allUsers = _loginManager.GetManageAndTokenUsernames(),
anonymousUsername = Identity.AnonyomousUsername,
onlineResource = settings.OnlineResource,
outputUrl = settings.OutputUrl
});
});
}
[HttpPost]
async public Task<IActionResult> FolderSecurity()
{
return await SecureApiCall(async () =>
{
var folder = Request.Query["folder"].ToString().ToLower();
var mapService = _mapServiceMananger.MapServices.Where(s => s.Type == MapServiceType.Folder && s.Fullname?.ToLower() == folder).FirstOrDefault();
if (mapService == null)
{
throw new MapServerException("Unknown folder: " + folder);
}
var settings = await mapService.GetSettingsAsync();
settings.AccessRules = null; // Remove all
if (Request.Form != null)
{
var form = Request.Form;
foreach (var key in form.Keys)
{
if (key.Contains("~")) // username~accesstype or username~_interpreter
{
var username = key.Substring(0, key.IndexOf("~"));
var accessRule = settings.AccessRules?.Where(a => a.Username.ToLower() == username.ToLower()).FirstOrDefault();
if (accessRule == null)
{
accessRule = new MapServiceSettings.MapServiceAccess();
var rules = new List<IMapServiceAccess>();
if (settings.AccessRules != null)
{
rules.AddRange(settings.AccessRules);
}
rules.Add(accessRule);
settings.AccessRules = rules.ToArray();
}
accessRule.Username = username;
var rule = key.Substring(key.IndexOf("~") + 1, key.Length - key.IndexOf("~") - 1);
string serviceType = String.Empty;
if (rule == "_all")
{
serviceType = rule;
}
else if (rule.StartsWith("_") && _mapServiceMananger.Interpreters
.Select(t => new Framework.system.PlugInManager().CreateInstance<IServiceRequestInterpreter>(t))
.Where(i => "_" + i.IdentityName.ToLower() == rule.ToLower())
.Count() == 1) // Interpreter
{
serviceType = rule.ToLower();
}
else if (Enum.TryParse<FolderAccessTypes>(rule, true, out FolderAccessTypes accessType))
{
serviceType = accessType.ToString();
}
if (!String.IsNullOrWhiteSpace(serviceType))
{
if (Convert.ToBoolean(form[key]) == true)
{
accessRule.AddServiceType(serviceType);
}
else
{
accessRule.RemoveServiceType(serviceType);
}
}
}
else
{
switch (key)
{
case "advancedsettings_onlineresource":
settings.OnlineResource = String.IsNullOrWhiteSpace(form[key]) ? null : form[key].ToString();
break;
case "advancedsettings_outputurl":
settings.OutputUrl = String.IsNullOrWhiteSpace(form[key]) ? null : form[key].ToString();
break;
}
}
}
}
await mapService.SaveSettingsAsync();
return Json(new
{
success = true,
folder = await MapService2Json(mapService, settings)
});
});
}
#endregion
#region Security
public IActionResult TokenUsers()
{
return SecureApiCall(() =>
{
return Json(new { users = _loginManager.GetTokenUsernames() });
});
}
[HttpPost]
public IActionResult CreateTokenUser(CreateTokenUserModel model)
{
return SecureApiCall(() =>
{
model.NewUsername = model.NewUsername?.Trim() ?? String.Empty;
model.NewPassword = model.NewPassword?.Trim() ?? String.Empty;
if (String.IsNullOrWhiteSpace(model.NewUsername))
{
throw new MapServerException("Username is empty");
}
_loginManager.CreateTokenLogin(model.NewUsername.ToLower(), model.NewPassword);
return Json(new { success = true });
});
}
[HttpPost]
public IActionResult ChangeTokenUserPassword(ChangeTokenUserPasswordModel model)
{
return SecureApiCall(() =>
{
model.Username = model.Username?.Trim() ?? String.Empty;
model.NewPassword = model.NewPassword?.Trim() ?? String.Empty;
_loginManager.ChangeTokenUserPassword(model.Username, model.NewPassword);
return Json(new { success = true });
});
}
#endregion
#region Helper
private IActionResult SecureApiCall(Func<IActionResult> func)
{
try
{
var authToken = _loginManager.GetAuthToken(this.Request);
if (!authToken.IsManageUser)
{
throw new Exception("Not allowed");
}
return func.Invoke();
}
catch (NotAuthorizedException)
{
return Json(new { success = false, error = "not authorized" });
}
catch (MapServerException mse)
{
return Json(new { success = false, error = mse.Message });
}
catch (Exception)
{
return Json(new { success = false, error = "unknown error" });
}
}
async private Task<IActionResult> SecureApiCall(Func<Task<IActionResult>> func)
{
try
{
var authToken = _loginManager.GetAuthToken(this.Request);
if (!authToken.IsManageUser)
{
throw new Exception("Not allowed");
}
return await func.Invoke();
}
catch (NotAuthorizedException)
{
return Json(new { success = false, error = "not authorized" });
}
catch (MapServerException mse)
{
return Json(new { success = false, error = mse.Message });
}
catch (Exception)
{
return Json(new { success = false, error = "unknown error" });
}
}
async private Task<object> MapService2Json(IMapService mapService, IMapServiceSettings settings)
{
var status = settings?.Status ?? MapServiceStatus.Running;
if (status == MapServiceStatus.Running)
{
if (!_mapServiceMananger.Instance.IsLoaded(mapService.Name, mapService.Folder))
{
status = MapServiceStatus.Idle;
}
}
bool hasErrors = await _logger.LogFileExists(mapService.Fullname, loggingMethod.error);
return new
{
name = mapService.Name,
folder = mapService.Folder,
status = status.ToString().ToLower(),
hasSecurity = settings?.AccessRules != null && settings.AccessRules.Length > 0,
runningSince = settings?.Status == MapServiceStatus.Running && mapService.RunningSinceUtc.HasValue ?
mapService.RunningSinceUtc.Value.ToShortDateString() + " " + mapService.RunningSinceUtc.Value.ToLongTimeString() + " (UTC)" :
String.Empty,
hasErrors = hasErrors
};
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TO;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace DAL
{
public class CasoDeTesteDAL
{
private static List<CasoDeTesteTO> PreencherLista(DataTable dt)
{
List<CasoDeTesteTO> result = new List<CasoDeTesteTO>();
CasoDeTesteTO caso;
foreach (DataRow dr in dt.Rows)
{
caso = new CasoDeTesteTO();
caso.Id = Convert.ToInt32(dr["ID"].ToString());
caso.IdSubModulo = Convert.ToInt32(dr["ID_SUB_MODULO"].ToString());
caso.IdProjeto = Convert.ToInt32(dr["ID_PROJETO"].ToString());
caso.Letra = dr["VC_LETRA_MODULO"].ToString();
caso.Complexidade = Convert.ToInt32(dr["NR_COMPLEXIDADE"].ToString());
caso.Status = Convert.ToInt32(dr["NR_STATUS"].ToString());
caso.CasoAutomatico = Convert.ToChar(dr["ST_CASO_AUTOMATICO"].ToString());
caso.Situacao = Convert.ToChar(dr["ST_SITUACAO"].ToString());
caso.Prioridade = Convert.ToInt32(dr["NR_PRIORIDADE"].ToString());
caso.IdAnalista = Convert.ToInt32(dr["ID_ANALISTA"].ToString());
caso.IdTestador = Convert.ToInt32(dr["ID_TESTADOR"].ToString());
caso.Objetivo = dr["VC_OBJETIVO"].ToString();
caso.Condicao = dr["VC_CONDICAO"].ToString();
caso.Entrada = dr["VC_ENTRADA"].ToString();
caso.Procedimento = dr["VC_PROCEDIMENTO"].ToString();
caso.Saida = dr["VC_SAIDA"].ToString();
caso.Observacao = dr["VC_OBSERVACAO"].ToString();
caso.DtCadastro = Convert.ToDateTime(dr["DT_CADASTRO"].ToString());
caso.DtLiberacao = string.IsNullOrEmpty(dr["DT_LIBERACAO"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_LIBERACAO"].ToString());
caso.DtDistribuicao = string.IsNullOrEmpty(dr["DT_DISTRIBUICAO"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_DISTRIBUICAO"].ToString());
caso.DtExecucao = string.IsNullOrEmpty(dr["DT_EXECUCAO"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_EXECUCAO"].ToString()); ;
caso.DtRetorno = string.IsNullOrEmpty(dr["DT_RETORNO"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_RETORNO"].ToString());
caso.DtFatura = string.IsNullOrEmpty(dr["DT_FATURA"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_FATURA"].ToString());
caso.DtFaturaExecucao = string.IsNullOrEmpty(dr["DT_FATURA_EXECUCAO"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_FATURA_EXECUCAO"].ToString());
result.Add(caso);
}
return result;
}
private static CasoDeTesteTO Preencher(DataTable dt)
{
CasoDeTesteTO caso = new CasoDeTesteTO();
foreach (DataRow dr in dt.Rows)
{
caso.Id = Convert.ToInt32(dr["ID"].ToString());
caso.IdSubModulo = Convert.ToInt32(dr["ID_SUB_MODULO"].ToString());
caso.IdProjeto = Convert.ToInt32(dr["ID_PROJETO"].ToString());
caso.Letra = dr["VC_LETRA_MODULO"].ToString();
caso.Complexidade = Convert.ToInt32(dr["NR_COMPLEXIDADE"].ToString());
caso.Status = Convert.ToInt32(dr["NR_STATUS"].ToString());
caso.CasoAutomatico = Convert.ToChar(dr["ST_CASO_AUTOMATICO"].ToString());
caso.Situacao = Convert.ToChar(dr["ST_SITUACAO"].ToString());
caso.Prioridade = Convert.ToInt32(dr["NR_PRIORIDADE"].ToString());
caso.IdAnalista = Convert.ToInt32(dr["ID_ANALISTA"].ToString());
caso.IdTestador = Convert.ToInt32(dr["ID_TESTADOR"].ToString());
caso.Objetivo = dr["VC_OBJETIVO"].ToString();
caso.Condicao = dr["VC_CONDICAO"].ToString();
caso.Entrada = dr["VC_ENTRADA"].ToString();
caso.Procedimento = dr["VC_PROCEDIMENTO"].ToString();
caso.Saida = dr["VC_SAIDA"].ToString();
caso.Observacao = dr["VC_OBSERVACAO"].ToString();
caso.DtCadastro = Convert.ToDateTime(dr["DT_CADASTRO"].ToString());
caso.DtLiberacao = string.IsNullOrEmpty(dr["DT_LIBERACAO"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_LIBERACAO"].ToString());
caso.DtDistribuicao = string.IsNullOrEmpty(dr["DT_DISTRIBUICAO"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_DISTRIBUICAO"].ToString());
caso.DtExecucao = string.IsNullOrEmpty(dr["DT_EXECUCAO"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_EXECUCAO"].ToString()); ;
caso.DtRetorno = string.IsNullOrEmpty(dr["DT_RETORNO"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_RETORNO"].ToString());
caso.DtFatura = string.IsNullOrEmpty(dr["DT_FATURA"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_FATURA"].ToString());
caso.DtFaturaExecucao = string.IsNullOrEmpty(dr["DT_FATURA_EXECUCAO"].ToString()) ? DateTime.MinValue : Convert.ToDateTime(dr["DT_FATURA_EXECUCAO"].ToString());
}
return caso;
}
public static CasoDeTesteTO Obter(int pId, int pIdSubModulo, int pIdProjeto)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT * FROM TB_CASO_DE_TESTE WHERE ID = @id and ID_SUB_MODULO = @idSubModulo and ID_PROJETO=@idProjeto";
comando.Parameters.Add(new SqlParameter("id", pId));
comando.Parameters.Add(new SqlParameter("idSubModulo", pIdSubModulo));
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return Preencher(resultado);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterPorSubModuloProjeto(int pIdProjeto, int pIdSubModulo, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT * FROM TB_CASO_DE_TESTE where ID_PROJETO =@idProjeto and ID_SUB_MODULO=@idSubModulo and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("idSubModulo", pIdSubModulo));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterTodosPorModuloProjeto(int pIdProjeto, int pIdModulo, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT caso.ID,caso.ID_SUB_MODULO,caso.ID_PROJETO,caso.VC_LETRA_MODULO,caso.NR_PRIORIDADE,caso.NR_COMPLEXIDADE,caso.ST_SITUACAO,caso.NR_STATUS,caso.ID_TESTADOR,caso.ID_ANALISTA,caso.VC_OBJETIVO,caso.VC_CONDICAO,caso.VC_OBSERVACAO,caso.ST_CASO_AUTOMATICO,caso.VC_ENTRADA,caso.VC_PROCEDIMENTO,caso.VC_SAIDA,caso.ID_ESTRATEGIA,caso.DT_CADASTRO,caso.DT_LIBERACAO,caso.DT_DISTRIBUICAO,caso.DT_EXECUCAO,caso.DT_RETORNO,caso.DT_FATURA ,caso.DT_FATURA_EXECUCAO ,caso.VC_ARQUIVO FROM TB_CASO_DE_TESTE caso, TB_MODULO modulo where caso.ID_PROJETO =@idProjeto and caso.ID_SUB_MODULO = modulo.ID and modulo.ID_MODULO_PAI=@idModulo and caso.VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("idModulo", pIdModulo));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterTodosPorProjeto(int pIdProjeto, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT * FROM TB_CASO_DE_TESTE where ID_PROJETO =@idProjeto and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterTodosPorTestador(int pIdTestador, int pStatus, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT * FROM TB_CASO_DE_TESTE where ID_TESTADOR =@idTestador and NR_STATUS=@nrStatus and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idTestador", pIdTestador));
comando.Parameters.Add(new SqlParameter("nrStatus", pStatus));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
conn.Close();
}
}
//Status
public static List<CasoDeTesteTO> ObterTodosPorProjetoStatus(int pIdProjeto, int pStatus, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT * FROM TB_CASO_DE_TESTE where ID_PROJETO =@idProjeto and NR_STATUS=@status and NR_COMPLEXIDADE<>0 and NR_PRIORIDADE<>0 and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterTodosPorProjetoStatusPrioridade(int pIdProjeto, int pStatus, int pPrioridade, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT * FROM TB_CASO_DE_TESTE where ID_PROJETO =@idProjeto and NR_STATUS=@status and NR_COMPLEXIDADE<>0 and NR_PRIORIDADE=@prioridade and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("prioridade", pPrioridade));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterTodosPorProjetoStatusComplexidade(int pIdProjeto, int pStatus, int pComplexidade, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT * FROM TB_CASO_DE_TESTE where ID_PROJETO =@idProjeto and NR_STATUS=@status and NR_COMPLEXIDADE=@complexidade and NR_PRIORIDADE<>0 and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("complexidade", pComplexidade));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterTodosPorProjetoStatusComplexidadePrioridade(int pIdProjeto, int pStatus, int pComplexidade, int pPrioridade, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT * FROM TB_CASO_DE_TESTE where ID_PROJETO =@idProjeto and NR_STATUS=@status and NR_COMPLEXIDADE=@complexidade and NR_PRIORIDADE=@prioridade and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("prioridade", pPrioridade));
comando.Parameters.Add(new SqlParameter("complexidade", pComplexidade));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
conn.Close();
}
}
//---------------------------------------------
public static List<CasoDeTesteTO> ObterTodosPorModuloProjetoStatus(int pIdProjeto, int pIdModulo, int pStatus, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT caso.ID,caso.ID_SUB_MODULO,caso.VC_LETRA_MODULO,caso.ID_PROJETO ,caso.NR_PRIORIDADE ,caso.NR_COMPLEXIDADE,caso.ST_SITUACAO,caso.NR_STATUS,caso.ID_ANALISTA ,caso.ID_TESTADOR ,caso.VC_OBJETIVO,caso.VC_CONDICAO,caso.VC_OBSERVACAO, caso.VC_OBJETIVO,caso.VC_ENTRADA ,caso.VC_PROCEDIMENTO, caso.VC_SAIDA ,caso.ST_CASO_AUTOMATICO ,caso.DT_CADASTRO,caso.DT_LIBERACAO ,caso.DT_DISTRIBUICAO ,caso.DT_EXECUCAO,caso.DT_RETORNO ,caso.DT_FATURA ,caso.DT_FATURA_EXECUCAO FROM TB_CASO_DE_TESTE caso, TB_MODULO modulo where caso.ID_PROJETO =@idProjeto and caso.ID_SUB_MODULO = modulo.ID and modulo.ID_MODULO_PAI=@idModulo and caso.NR_STATUS=@status and caso.NR_COMPLEXIDADE<>0 and caso.NR_PRIORIDADE<>0 and caso.VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("idModulo", pIdModulo));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterTodosPorModuloProjetoStatusPrioridade(int pIdProjeto, int pIdModulo, int pStatus, int pPrioridade, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT caso.ID,caso.ID_SUB_MODULO,caso.VC_LETRA_MODULO,caso.ID_PROJETO ,caso.NR_PRIORIDADE ,caso.NR_COMPLEXIDADE,caso.ST_SITUACAO,caso.NR_STATUS,caso.ID_ANALISTA ,caso.ID_TESTADOR ,caso.VC_OBJETIVO,caso.VC_CONDICAO,caso.VC_OBSERVACAO, caso.VC_OBJETIVO,caso.VC_ENTRADA ,caso.VC_PROCEDIMENTO, caso.VC_SAIDA ,caso.ST_CASO_AUTOMATICO ,caso.DT_CADASTRO,caso.DT_LIBERACAO ,caso.DT_DISTRIBUICAO ,caso.DT_EXECUCAO,caso.DT_RETORNO ,caso.DT_FATURA ,caso.DT_FATURA_EXECUCAO FROM TB_CASO_DE_TESTE caso, TB_MODULO modulo where caso.ID_PROJETO =@idProjeto and caso.ID_SUB_MODULO = modulo.ID and modulo.ID_MODULO_PAI=@idModulo and caso.NR_STATUS=@status and caso.NR_COMPLEXIDADE<>0 and caso.NR_PRIORIDADE=@prioridade and caso.VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("idModulo", pIdModulo));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("prioridade", pPrioridade));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterTodosPorModuloProjetoStatusComplexidade(int pIdProjeto, int pIdModulo, int pStatus, int pComplexidade, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT caso.ID,caso.ID_SUB_MODULO,caso.ID_PROJETO,caso.VC_LETRA_MODULO,caso.NR_PRIORIDADE ,caso.NR_COMPLEXIDADE,caso.ST_SITUACAO,caso.NR_STATUS,caso.ID_ANALISTA ,caso.ID_TESTADOR ,caso.VC_OBJETIVO,caso.VC_CONDICAO,caso.VC_OBSERVACAO, caso.VC_OBJETIVO,caso.VC_ENTRADA ,caso.VC_PROCEDIMENTO, caso.VC_SAIDA ,caso.ST_CASO_AUTOMATICO ,caso.DT_CADASTRO,caso.DT_LIBERACAO ,caso.DT_DISTRIBUICAO ,caso.DT_EXECUCAO,caso.DT_RETORNO ,caso.DT_FATURA ,caso.DT_FATURA_EXECUCAO FROM TB_CASO_DE_TESTE caso, TB_MODULO modulo where caso.ID_PROJETO =@idProjeto and caso.ID_SUB_MODULO = modulo.ID and modulo.ID_MODULO_PAI=@idModulo and caso.NR_STATUS=@status and caso.NR_COMPLEXIDADE=@complexidade and caso.NR_PRIORIDADE<>0 and caso.VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("idModulo", pIdModulo));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("complexidade", pComplexidade));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterTodosPorModuloProjetoStatusComplexidadePrioridade(int pIdProjeto, int pIdModulo, int pStatus, int pComplexidade, int pPrioridade, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT caso.ID,caso.ID_SUB_MODULO,caso.ID_PROJETO,caso.VC_LETRA_MODULO,caso.NR_PRIORIDADE ,caso.NR_COMPLEXIDADE,caso.ST_SITUACAO,caso.NR_STATUS,caso.ID_ANALISTA ,caso.ID_TESTADOR ,caso.VC_OBJETIVO,caso.VC_CONDICAO,caso.VC_OBSERVACAO, caso.VC_OBJETIVO,caso.VC_ENTRADA ,caso.VC_PROCEDIMENTO, caso.VC_SAIDA ,caso.ST_CASO_AUTOMATICO ,caso.DT_CADASTRO,caso.DT_LIBERACAO ,caso.DT_DISTRIBUICAO ,caso.DT_EXECUCAO,caso.DT_RETORNO ,caso.DT_FATURA ,caso.DT_FATURA_EXECUCAO FROM TB_CASO_DE_TESTE caso, TB_MODULO modulo where caso.ID_PROJETO =@idProjeto and caso.ID_SUB_MODULO = modulo.ID and modulo.ID_MODULO_PAI=@idModulo and caso.NR_STATUS=@status and caso.NR_COMPLEXIDADE=@complexidade and caso.NR_PRIORIDADE=@prioridade and caso.VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("idModulo", pIdModulo));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("prioridade", pPrioridade));
comando.Parameters.Add(new SqlParameter("complexidade", pComplexidade));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
finally
{
conn.Close();
}
}
//---------------------------------------------
public static List<CasoDeTesteTO> ObterPorSubModuloProjetoStatus(int pIdProjeto, int pIdSubModulo, int pStatus, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = " SELECT * FROM TB_CASO_DE_TESTE where ID_PROJETO =@idProjeto and ID_SUB_MODULO=@idSubModulo and NR_STATUS=@status and NR_COMPLEXIDADE<>0 and NR_PRIORIDADE<>0 and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("idSubModulo", pIdSubModulo));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterPorSubModuloProjetoStatusPrioridade(int pIdProjeto, int pIdSubModulo, int pStatus, int pPrioridade, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = " SELECT * FROM TB_CASO_DE_TESTE where ID_PROJETO =@idProjeto and ID_SUB_MODULO=@idSubModulo and NR_STATUS=@status and NR_PRIORIDADE=@prioridade and NR_COMPLEXIDADE<>0 and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("idSubModulo", pIdSubModulo));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("prioridade", pPrioridade));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterPorSubModuloProjetoStatusComplexidade(int pIdProjeto, int pIdSubModulo, int pStatus, int pComplexidade, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = " SELECT * FROM TB_CASO_DE_TESTE where ID_PROJETO =@idProjeto and ID_SUB_MODULO=@idSubModulo and NR_STATUS=@status and NR_COMPLEXIDADE=@complexidade and NR_PRIORIDADE<>0 and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("idSubModulo", pIdSubModulo));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("complexidade", pComplexidade));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
finally
{
conn.Close();
}
}
public static List<CasoDeTesteTO> ObterPorSubModuloProjetoStatusComplexidadePrioridade(int pIdProjeto, int pIdSubModulo, int pStatus, int pComplexidade, int pPrioridade, string pObjetivo)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = " SELECT * FROM TB_CASO_DE_TESTE where ID_PROJETO =@idProjeto and ID_SUB_MODULO=@idSubModulo and NR_STATUS=@status and NR_COMPLEXIDADE=@complexidade and NR_PRIORIDADE=@prioridade and VC_OBJETIVO like @objetivo";
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("idSubModulo", pIdSubModulo));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Parameters.Add(new SqlParameter("prioridade", pPrioridade));
comando.Parameters.Add(new SqlParameter("complexidade", pComplexidade));
comando.Parameters.Add(new SqlParameter("objetivo", "%" + pObjetivo + "%"));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
return PreencherLista(resultado);
}
finally
{
conn.Close();
}
}
public static void Cadastrar(CasoDeTesteTO pCaso)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "insert into TB_CASO_DE_TESTE (ID ,ID_SUB_MODULO,ID_PROJETO,VC_LETRA_MODULO,NR_PRIORIDADE,NR_COMPLEXIDADE,ST_SITUACAO,NR_STATUS,ID_ANALISTA,VC_OBJETIVO,VC_CONDICAO,VC_OBSERVACAO,ST_CASO_AUTOMATICO,DT_CADASTRO, VC_ENTRADA, VC_PROCEDIMENTO, VC_SAIDA,ID_TESTADOR) values (@id, @idSubModulo,@idProjeto,@letra,@nrPrioridade,@complexidade,@situacao,@status,@idAnalista,@objetivo,@condicao,@observacao,@casoAutomatico,@dtCadastro, @entrada, @procedimento ,@saida,@idTestador)";
comando.Parameters.Add(new SqlParameter("id", pCaso.Id));
comando.Parameters.Add(new SqlParameter("idSubModulo", pCaso.IdSubModulo));
comando.Parameters.Add(new SqlParameter("idProjeto", pCaso.IdProjeto));
comando.Parameters.Add(new SqlParameter("letra", pCaso.Letra));
comando.Parameters.Add(new SqlParameter("nrPrioridade", pCaso.Prioridade));
comando.Parameters.Add(new SqlParameter("complexidade", pCaso.Complexidade));
comando.Parameters.Add(new SqlParameter("situacao", pCaso.Situacao));
comando.Parameters.Add(new SqlParameter("status", pCaso.Status));
comando.Parameters.Add(new SqlParameter("idAnalista", pCaso.IdAnalista));
comando.Parameters.Add(new SqlParameter("idTestador", pCaso.IdTestador));
comando.Parameters.Add(new SqlParameter("objetivo", pCaso.Objetivo));
comando.Parameters.Add(new SqlParameter("condicao", pCaso.Condicao));
comando.Parameters.Add(new SqlParameter("observacao", pCaso.Observacao));
comando.Parameters.Add(new SqlParameter("casoAutomatico", pCaso.CasoAutomatico));
comando.Parameters.Add(new SqlParameter("dtCadastro", DateTime.Now));
comando.Parameters.Add(new SqlParameter("entrada", pCaso.Entrada));
comando.Parameters.Add(new SqlParameter("procedimento", pCaso.Procedimento));
comando.Parameters.Add(new SqlParameter("saida", pCaso.Saida));
comando.Connection = conn;
conn.Open();
comando.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new ApplicationException("Falha ao cadastrar o caso de teste");
}
finally
{
conn.Close();
}
}
public static int Alterar(CasoDeTesteTO pCaso)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
SqlDateTime sqldatenull = SqlDateTime.Null;
comando.CommandText = "update TB_CASO_DE_TESTE set NR_PRIORIDADE=@nrPrioridade,NR_COMPLEXIDADE=@complexidade,ST_SITUACAO=@situacao,NR_STATUS=@status,ID_ANALISTA=@idAnalista,ID_TESTADOR=@idTestador,VC_OBJETIVO=@objetivo,VC_CONDICAO=@condicao,VC_OBSERVACAO=@observacao,ST_CASO_AUTOMATICO=@casoAutomatico,DT_LIBERACAO=@dtLiberacao,DT_DISTRIBUICAO=@dtDistribuicao,DT_EXECUCAO=@dtExecucao,DT_RETORNO=@dtRetorno,DT_FATURA=@dtFatura,DT_FATURA_EXECUCAO=@dtFaturaExecucao, VC_ENTRADA=@entrada, VC_PROCEDIMENTO=@procedimento, VC_SAIDA=@saida where ID=@id and ID_SUB_MODULO=@idSubModulo and ID_PROJETO=@idProjeto ";
comando.Parameters.Add(new SqlParameter("id", pCaso.Id));
comando.Parameters.Add(new SqlParameter("idSubModulo", pCaso.IdSubModulo));
comando.Parameters.Add(new SqlParameter("idProjeto", pCaso.IdProjeto));
comando.Parameters.Add(new SqlParameter("nrPrioridade", pCaso.Prioridade));
comando.Parameters.Add(new SqlParameter("complexidade", pCaso.Complexidade));
comando.Parameters.Add(new SqlParameter("situacao", pCaso.Situacao));
comando.Parameters.Add(new SqlParameter("status", pCaso.Status));
comando.Parameters.Add(new SqlParameter("idAnalista", pCaso.IdAnalista));
comando.Parameters.Add(new SqlParameter("idTestador", pCaso.IdTestador));
comando.Parameters.Add(new SqlParameter("objetivo", pCaso.Objetivo));
comando.Parameters.Add(new SqlParameter("condicao", pCaso.Condicao));
comando.Parameters.Add(new SqlParameter("observacao", pCaso.Observacao));
comando.Parameters.Add(new SqlParameter("dtCadastro", pCaso.DtCadastro));
comando.Parameters.Add(new SqlParameter("casoAutomatico", pCaso.CasoAutomatico));
comando.Parameters.Add(new SqlParameter("entrada", pCaso.Entrada));
comando.Parameters.Add(new SqlParameter("procedimento", pCaso.Procedimento));
comando.Parameters.Add(new SqlParameter("saida", pCaso.Saida));
// Estava dando erro nas datas nulas
if (string.IsNullOrEmpty(pCaso.DtLiberacao.ToString()))
{
comando.Parameters.Add(new SqlParameter("dtLiberacao", sqldatenull));
}
else
{
comando.Parameters.Add(new SqlParameter("dtLiberacao", pCaso.DtLiberacao));
}
if (string.IsNullOrEmpty(pCaso.DtDistribuicao.ToString()))
{
comando.Parameters.Add(new SqlParameter("dtDistribuicao", sqldatenull));
}
else
{
comando.Parameters.Add(new SqlParameter("dtDistribuicao", pCaso.DtDistribuicao));
}
if (string.IsNullOrEmpty(pCaso.DtExecucao.ToString()))
{
comando.Parameters.Add(new SqlParameter("dtExecucao", sqldatenull));
}
else
{
comando.Parameters.Add(new SqlParameter("dtExecucao", pCaso.DtExecucao));
}
if (string.IsNullOrEmpty(pCaso.DtRetorno.ToString()))
{
comando.Parameters.Add(new SqlParameter("dtRetorno", sqldatenull));
}
else
{
comando.Parameters.Add(new SqlParameter("dtRetorno", pCaso.DtRetorno));
}
if (string.IsNullOrEmpty(pCaso.DtFatura.ToString()))
{
comando.Parameters.Add(new SqlParameter("dtFatura", sqldatenull));
}
else
{
comando.Parameters.Add(new SqlParameter("dtFatura", pCaso.DtFatura));
}
if (string.IsNullOrEmpty(pCaso.DtFaturaExecucao.ToString()))
{
comando.Parameters.Add(new SqlParameter("dtFaturaExecucao", sqldatenull));
}
else
{
comando.Parameters.Add(new SqlParameter("dtFaturaExecucao", pCaso.DtFaturaExecucao));
}
comando.Connection = conn;
conn.Open();
return comando.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new ApplicationException("Falha ao alterar o caso de teste");
}
finally
{
conn.Close();
}
}
public static int AlterarStatus(CasoDeTesteTO pCaso, int pStatus)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
SqlDateTime sqldatenull = SqlDateTime.Null;
comando.CommandText = "update TB_CASO_DE_TESTE set NR_STATUS=@status where ID=@id and ID_SUB_MODULO=@idSubModulo and ID_PROJETO=@idProjeto ";
comando.Parameters.Add(new SqlParameter("id", pCaso.Id));
comando.Parameters.Add(new SqlParameter("idSubModulo", pCaso.IdSubModulo));
comando.Parameters.Add(new SqlParameter("idProjeto", pCaso.IdProjeto));
comando.Parameters.Add(new SqlParameter("status", pStatus));
comando.Connection = conn;
conn.Open();
return comando.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new ApplicationException("Falha ao alterar o status do caso de teste");
}
finally
{
conn.Close();
}
}
public static int LiberarCasoDeTeste(CasoDeTesteTO pCaso)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
SqlDateTime sqldatenull = SqlDateTime.Null;
comando.CommandText = "update TB_CASO_DE_TESTE set NR_STATUS=@status, DT_LIBERACAO=@dtLiberacao where ID=@id and ID_SUB_MODULO=@idSubModulo and ID_PROJETO=@idProjeto ";
comando.Parameters.Add(new SqlParameter("id", pCaso.Id));
comando.Parameters.Add(new SqlParameter("idSubModulo", pCaso.IdSubModulo));
comando.Parameters.Add(new SqlParameter("idProjeto", pCaso.IdProjeto));
comando.Parameters.Add(new SqlParameter("status", pCaso.Status));
comando.Parameters.Add(new SqlParameter("dtLiberacao", pCaso.DtLiberacao));
comando.Connection = conn;
conn.Open();
return comando.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new ApplicationException("Falha ao alterar o status do caso de teste");
}
finally
{
conn.Close();
}
}
public static int DistribuirCasoDeTeste(CasoDeTesteTO pCaso)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
SqlDateTime sqldatenull = SqlDateTime.Null;
comando.CommandText = "update TB_CASO_DE_TESTE set NR_STATUS=@status, DT_DISTRIBUICAO=@dtDistribuicao, ID_TESTADOR=@idTestador where ID=@id and ID_SUB_MODULO=@idSubModulo and ID_PROJETO=@idProjeto ";
comando.Parameters.Add(new SqlParameter("id", pCaso.Id));
comando.Parameters.Add(new SqlParameter("idSubModulo", pCaso.IdSubModulo));
comando.Parameters.Add(new SqlParameter("idProjeto", pCaso.IdProjeto));
comando.Parameters.Add(new SqlParameter("status", pCaso.Status));
comando.Parameters.Add(new SqlParameter("dtDistribuicao", pCaso.DtDistribuicao));
comando.Parameters.Add(new SqlParameter("idTestador", pCaso.IdTestador));
comando.Connection = conn;
conn.Open();
return comando.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new ApplicationException("Falha ao alterar o status do caso de teste");
}
finally
{
conn.Close();
}
}
public static int Excluir(int pID, int pIdSubModulo, int pIdProjeto)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "delete from TB_CASO_DE_TESTE where ID = @id and ID_SUB_MODULO = @idSubModulo and ID_PROJETO = @idProjeto ";
comando.Parameters.Add(new SqlParameter("id", pID));
comando.Parameters.Add(new SqlParameter("idSubModulo", pIdSubModulo));
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Connection = conn;
conn.Open();
return comando.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
/// <summary>
/// Verifica se um sub-modulo possui algum caso de teste cadastrado.
/// </summary>
/// <param name="pIdModulo"></param>
/// <param name="pIdProjeto"></param>
/// <returns></returns>
public static bool VerificarCasosPorModulo(int pIdSubModulo, int pIdProjeto)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "select COUNT(*) from TB_CASO_DE_TESTE where ID_SUB_MODULO = @idSubModulo and ID_PROJETO = @idProjeto";
comando.Parameters.Add(new SqlParameter("idModulo", pIdSubModulo));
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
int qtd = 0;
foreach (DataRow dr in resultado.Rows)
{
qtd = Convert.ToInt32(dr[0].ToString());
}
return qtd == 0 ? true : false;
}
catch (Exception ex)
{
throw new ApplicationException("Falha ao excluir o módulo");
}
finally
{
conn.Close();
}
}
/// <summary>
/// Obter proximo id da lista de casos do submodulo projeto
/// </summary>
/// <param name="pIdProjeto"></param>
/// <param name="pIdSubModulo"></param>
/// <returns></returns>
public static int ObterProximoID(int pIdSubModulo, int pIdProjeto)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
comando.CommandText = "SELECT MAX(ID) FROM TB_CASO_DE_TESTE WHERE ID_SUB_MODULO = @idSubModulo and ID_PROJETO=@idProjeto";
comando.Parameters.Add(new SqlParameter("idSubModulo", pIdSubModulo));
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Connection = conn;
conn.Open();
DataTable resultado = new DataTable();
resultado.Load(comando.ExecuteReader());
int max = 0;
foreach (DataRow dr in resultado.Rows)
{
if (string.IsNullOrEmpty(dr[0].ToString()))
{
max = 1;
}
else
{
max = Convert.ToInt32(dr[0].ToString()) + 1;
}
}
return max;
}
finally
{
conn.Close();
}
}
public static int AlterarTestador(int pIdCaso, int pIdSubModulo, int pIdProjeto, int pIdTestador)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Conexao.ConnectionString;
try
{
SqlCommand comando = new SqlCommand();
SqlDateTime sqldatenull = SqlDateTime.Null;
comando.CommandText = "update TB_CASO_DE_TESTE set ID_TESTADOR=@testador where ID=@id and ID_SUB_MODULO=@idSubModulo and ID_PROJETO=@idProjeto ";
comando.Parameters.Add(new SqlParameter("id", pIdCaso));
comando.Parameters.Add(new SqlParameter("idSubModulo", pIdSubModulo));
comando.Parameters.Add(new SqlParameter("idProjeto", pIdProjeto));
comando.Parameters.Add(new SqlParameter("testador", pIdTestador));
comando.Connection = conn;
conn.Open();
return comando.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new ApplicationException("Falha ao alterar o testador do caso de teste");
}
finally
{
conn.Close();
}
}
}
}
|
// Copyright (c) 2020, mParticle, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace MP.Json
{
/// <summary>
/// This class is meant to support very lightweight JSON trees that use the minimum amount of memory.
/// The footprint of the JSON trees are meant to be similar to the equivalent representation of the
/// the JSON data as a text string.
///
/// There could be thousands of these trees in memory. Existing object trees from Newtonsoft JSON.NET,
/// ManateeJSON and others have a lot of unnecessary overhead.
///
/// Data is stored as raw objects:
/// Nulls are represented as DBNullValue.
/// Strings are represented as strings but we share instances with a small lru.
/// Booleans are stored as shared objects.
/// Numbers are normally stored as doubles just as in Javascript,
/// they are converted to doubles with possible loss of precision.
/// Arrays are normally stored and optimized for object[]
/// Objects are normally stored and optimized for SORTED KeyValuePair(string,object)[],
/// </summary>
public struct MPJson : IEquatable<MPJson>, IEnumerable<MPJson>, IFormattable
{
#region Constants
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
const int MaxDepth = 1000;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static readonly MPJson True = MPJson.From(JsonParser.True);
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static readonly MPJson False = MPJson.From(JsonParser.False);
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static readonly MPJson Null = MPJson.From(DBNull.Value);
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static readonly MPJson Zero = new MPJson(0.0);
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static readonly MPJson Undefined = new MPJson();
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private static Comparison<KeyValuePair<string, object>> KeyComparer = (a, b) => string.CompareOrdinal(a.Key, b.Key);
#endregion
#region Variables
public object Value;
#endregion
#region Json
/// <summary>
/// Produces a JSON object for numbers with coercion to double
/// </summary>
public MPJson(double value)
{
Value = value;
}
/// <summary>
/// Produce a json string object
/// </summary>
/// <param name="s"></param>
public MPJson(string s)
{
Value = s != null ? (object)s : DBNull.Value;
}
/// <summary>
/// Produces a json object for booleans
/// </summary>
public MPJson(bool b)
{
Value = b ? JsonParser.True : JsonParser.False;
}
/// <summary>
/// Creates an objects from the properties
/// </summary>
/// <param name="array"></param>
[DebuggerStepThrough]
public static MPJson Object(params KeyValuePair<string, object>[] array)
{
// We know params was used, otherwise the other method would have been called!
return Object(array, true);
}
public static MPJson Object(KeyValuePair<string, object>[] array, bool keep = false)
{
if (!keep)
array = (KeyValuePair<string, object>[])array.Clone();
System.Array.Sort(array, KeyComparer);
return new MPJson { Value = array };
}
/// <summary>
/// Creates an objects from the properties entered as flattened pairs
/// </summary>
/// <param name="pairs"></param>
public static MPJson Object(params MPJson[] pairs)
{
if ((pairs.Length & 1) == 1)
throw new ArgumentException("An even number of parameters must be passed", nameof(pairs));
int length = pairs.Length >> 1;
var kvarray = new KeyValuePair<string, object>[length];
for (int i = 0; i < length; i++)
kvarray[i] = new KeyValuePair<string, object>((string)pairs[i * 2], pairs[i * 2 + 1].Value);
return Object(kvarray);
}
/// <summary>
/// Empty object
/// </summary>
/// <returns></returns>
public static MPJson Object() => new MPJson { Value = System.Array.Empty<KeyValuePair<string, object>>() };
/// <summary>
/// Construct Json from array
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static MPJson Array(params MPJson[] array)
{
object[] jarray = new object[array.Length];
for (int i = 0; i < array.Length; i++)
jarray[i] = array[i].Value;
return new MPJson { Value = jarray };
}
/// <summary>
/// Construct Json from arbitrary object
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static MPJson From(object obj) => new MPJson { Value = obj };
#endregion
#region Properties
/// <summary>
/// Returns the type of the object
/// </summary>
public JsonType Type => GetType(Value);
/// <summary>
/// Returns the element at array index, otherwise undefined for other types
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public MPJson this[int index]
=> Value is object[] array
&& unchecked((uint)index < (uint)array.Length) ? MPJson.From(array[index]) : (default);
/// <summary>
/// Returns the value for key property, otherwise undefined for other types
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
public MPJson this[string property]
=> Value is KeyValuePair<string, object>[] map
? MPJson.From(map.GetProperty(property))
: default;
/// <summary>
/// Returns if Json object is undefined
/// </summary>
public bool IsUndefined => Value == null;
/// <summary>
/// Returns if Json object has value
/// </summary>
public bool HasValue => Value != null;
public int Length => Value is Array array ? array.Length : 0;
/// <summary>
/// Shortcut for new JsonProperty
/// </summary>
[DebuggerStepThrough]
public static JsonProperty Property(string keyword, MPJson json)
=> new JsonProperty(keyword, json);
#endregion
#region Enumerable
/// <summary>
/// Returns keys of objects
/// </summary>
/// <returns></returns>
public IEnumerable<string> Keys
{
get
{
if (Value is KeyValuePair<string, object>[] properties)
foreach (var v in properties)
yield return v.Key;
}
}
/// <summary>
/// Returns property pairs of objects
/// </summary>
/// <returns></returns>
public IEnumerable<JsonProperty> Properties
{
get
{
if (Value is KeyValuePair<string, object>[] properties)
foreach (var v in properties)
yield return new JsonProperty(v.Key, MPJson.From(v.Value));
}
}
/// <summary>
/// Returns array elements
/// </summary>
public IEnumerator<MPJson> GetEnumerator()
{
if (Value is object[] array)
foreach (object v in array)
yield return MPJson.From(v);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Conversions
public static explicit operator string(MPJson json) => (string)json.Value;
public static explicit operator double(MPJson json) => Convert.ToDouble(json.Value);
public static explicit operator object[](MPJson json) => (object[])json.Value;
public static explicit operator bool(MPJson json) => (bool)json.Value;
public static implicit operator MPJson(string value) => new MPJson(value);
public static implicit operator MPJson(double value) => new MPJson(value);
public static implicit operator MPJson(bool value) => new MPJson(value);
public static implicit operator MPJson(MPJson[] value) => MPJson.Array(value);
#endregion
#region Methods
/// <summary>
/// Parses a json string
/// </summary>
/// <param name="s"></param>
/// <returns>
/// Return json object or FormatException on failure
/// </returns>
public static MPJson Parse(string s) => new JsonParser().Parse(s);
/// <summary>
/// Parses a json reader
/// </summary>
/// <param name="reader"></param>
/// <returns>
/// Return json object or FormatException on failure
/// </returns>
public static MPJson Parse(TextReader reader) => new JsonParser().Parse(reader);
/// <summary>
/// Attempts to parse a json string
/// </summary>
/// <param name="reader"></param>
/// <returns>a json object, which may be undefined on failure (IsUndefined=true, HasValue=false)</returns>
public static bool TryParse(string s, out MPJson json) => new JsonParser().TryParse(s, out json);
/// <summary>
/// Attempts to parse a json reader
/// </summary>
/// <param name="reader"></param>
/// <returns>a json object, which may be undefined on failure (IsUndefined=true, HasValue=false)</returns>
public static bool TryParse(TextReader reader, out MPJson json) => new JsonParser().TryParse(reader, out json);
#endregion
#region Formatter
/// <summary>
/// Renders a string representation of the JSON
/// </summary>
public override string ToString() => ToString(null, null);
/// <summary>
/// Provides for multiple different string formatting options
///
/// This is to allow for multiline, indented json in the future
/// </summary>
/// <param name="format"></param>
/// <param name="provider"></param>
/// <returns></returns>
public string ToString(string format, IFormatProvider provider)
{
var builder = new StringBuilder();
Write(builder, Value);
return builder.ToString();
}
private static void Write(StringBuilder builder, object obj)
{
var type = GetType(obj);
switch (type)
{
case JsonType.String:
Write(builder, (string)obj);
break;
case JsonType.Object:
builder.Append('{');
bool first = true;
foreach (var v in (IEnumerable<KeyValuePair<string, object>>)obj)
{
if (!first) builder.Append(',');
builder.Append(' ');
Write(builder, v.Key);
builder.Append(':');
Write(builder, v.Value);
first = false;
}
builder.Append(' ').Append('}');
break;
case JsonType.Array:
builder.Append('[');
first = true;
foreach (object v in (IEnumerable<object>)obj)
{
if (!first) builder.Append(',');
builder.Append(' ');
Write(builder, v);
first = false;
}
builder.Append(' ').Append(']');
break;
case JsonType.Boolean:
builder.Append(((bool)obj) ? JsonParser.TrueKeyword : JsonParser.FalseKeyword);
break;
case JsonType.Null:
builder.Append(JsonParser.NullKeyword);
break;
case JsonType.Undefined:
builder.Append(JsonParser.UndefinedKeyword);
break;
default:
builder.Append(obj);
break;
}
}
private static void Write(StringBuilder builder, string s)
{
builder.Append('"');
foreach (char ch in s)
{
if (ch >= ' ')
{
if (ch == '"' || ch == '\\')
builder.Append('\\');
builder.Append(ch);
}
else
{
builder.Append('\\');
switch (ch)
{
case '\t':
builder.Append('t');
break;
case '\n':
builder.Append('n');
break;
case '\r':
builder.Append('r');
break;
case '\f':
builder.Append('f');
break;
default:
builder.Append('u').Append(((int)ch).ToString("x4"));
break;
}
}
}
builder.Append('"');
}
#endregion
#region Equality Operations
/// <summary>
/// Indicates whether two Json objects are equivalent
/// </summary>
/// <param name="obj1"></param>
/// <param name="obj2"></param>
/// <param name="depth">set to zero; used for catching stack overflows </param>
/// <returns></returns>
public static bool operator ==(MPJson object1, MPJson object2)
=> Matches(object1.Value, object2.Value);
public static bool operator !=(MPJson object1, MPJson object2)
=> !Matches(object1.Value, object2.Value);
public bool Equals(MPJson obj)
=> Matches(Value, obj.Value);
public override bool Equals(object obj)
=> obj is MPJson && Equals((MPJson)obj);
public override int GetHashCode()
{
return GetHashCode(Value);
}
private static int GetHashCode(object value)
{
if (value == null) return 0x12345678;
int hashCode = unchecked((int)0xDEADBEEF);
if (value is object[] array)
{
foreach (object v in array)
hashCode = CombineHashcode(hashCode, GetHashCode(v));
return hashCode;
}
else if (value is KeyValuePair<string, object>[] obj)
{
foreach (var kv in obj)
hashCode ^= CombineHashcode(GetHashCode(kv.Key), GetHashCode(kv.Value));
return hashCode;
}
return hashCode ^ value.GetHashCode();
}
private static int CombineHashcode(int h1, int h2)
{
return h1 * 3777 ^ h2;
}
public static bool Matches(object obj1, object obj2, int depth = 0)
{
if (obj1 == null || obj2 == null) return obj1 == obj2;
if (obj1.Equals(obj2)) return true;
if (depth >= MaxDepth)
throw new StackOverflowException("Json too large"); // catchable stack overflow
JsonType type1 = GetType(obj1);
JsonType type2 = GetType(obj2);
if (type1 != type2)
return false;
switch (type1)
{
case JsonType.Number:
if (GetType(obj2) != JsonType.Number) break;
return Convert.ToDouble(obj1) == Convert.ToDouble(obj2);
case JsonType.Array:
var array1 = (IList)obj1;
var array2 = (IList)obj2;
int count = array1.Count;
if (count != array2.Count)
return false;
for (int i = 0; i < count; i++)
if (!Matches(array1[i], array2[i], depth + 1))
return false;
return true;
case JsonType.Object:
// Handle JsonLite values here...
if (obj1 is KeyValuePair<string, object>[] kvlist1
&& obj2 is KeyValuePair<string, object>[] kvlist2)
{
count = kvlist1.Length;
if (count != kvlist2.Length)
return false;
for (int i = 0; i < count; i++)
if (kvlist1[i].Key != kvlist2[i].Key
|| !Matches(kvlist1[i].Value, kvlist2[i].Value, depth + 1))
return false;
return true;
}
return false;
case JsonType.String:
case JsonType.Boolean:
case JsonType.Null:
// These cases are handled at the beginning of the function
break;
}
return false;
}
#endregion
#region Conversion
/// <summary>
/// Gets the type of a Json object
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static JsonType GetType(object obj)
{
if (obj == null)
return JsonType.Undefined;
// Not sure which is faster
TypeCode typeCode = System.Type.GetTypeCode(obj.GetType());
// TypeCode typeCode = obj is IConvertible iconv ? iconv.GetTypeCode() : TypeCode.Object;
switch (typeCode)
{
case TypeCode.String:
return JsonType.String;
case TypeCode.Double:
return JsonType.Number;
case TypeCode.DBNull:
return JsonType.Null;
case TypeCode.Boolean:
return JsonType.Boolean;
}
if (obj is KeyValuePair<string, object>[])
return JsonType.Object;
if (obj is object[])
return JsonType.Array;
return JsonType.Unknown;
}
#endregion
#region Functional routines
public static object MapChildren(object obj, Func<object, object> func)
{
if (obj is KeyValuePair<string, object>[] map)
{
KeyValuePair<string, object>[] result = map;
for (int i = 0; i < map.Length; i++)
{
var kv = map[i];
object mappedChild = func(kv.Value);
if (mappedChild == null) return null;
if (mappedChild != kv.Value)
{
result = (KeyValuePair<string, object>[])map.Clone();
result[i] = new KeyValuePair<string, object>(kv.Key, mappedChild);
for (i++; i < map.Length; i++)
{
kv = map[i];
mappedChild = func(kv.Value);
if (mappedChild == null) return null;
result[i] = new KeyValuePair<string, object>(kv.Key, mappedChild);
}
}
}
return result;
}
else if (obj is object[] array)
{
object[] result = array;
for (int i = 0; i < array.Length; i++)
{
object child = array[i];
object mappedChild = func(child);
if (mappedChild == null) return null;
if (mappedChild != child)
{
result = (object[])array.Clone();
result[i] = mappedChild;
for (i++; i < array.Length; i++)
{
child = array[i];
mappedChild = func(child);
if (mappedChild == null) return null;
result[i] = mappedChild;
}
}
}
return result;
}
return obj;
}
/// <summary>
/// Transform every object in tree while reusing any unchanged objects
/// If func is null on any object, the whole result is null
/// </summary>
/// <param name="obj"></param>
/// <param name="func"></param>
/// <returns>
/// </returns>
/// <remarks>
/// This methods is useful for many different task.
/// -- Searching for objects
/// - func returns same object if not found, or null if found
/// -- Make modifications to objects
/// </remarks>
public static object MapAll(object obj, Func<object, object> func)
{
object result = obj;
if (obj is KeyValuePair<string, object>[] map)
{
KeyValuePair<string, object>[] resultMap = map;
for (int i = 0; i < map.Length; i++)
{
var kv = map[i];
object mappedChild = MapAll(kv.Value, func);
if (mappedChild == null) return null;
if (mappedChild != kv.Value)
{
resultMap = (KeyValuePair<string, object>[])map.Clone();
resultMap[i] = new KeyValuePair<string, object>(kv.Key, mappedChild);
for (i++; i < map.Length; i++)
{
kv = map[i];
mappedChild = MapAll(kv.Value, func);
if (mappedChild == null) return null;
resultMap[i] = new KeyValuePair<string, object>(kv.Key, mappedChild);
}
}
}
result = resultMap;
}
else if (obj is object[] array)
{
object[] resultArray = array;
for (int i = 0; i < array.Length; i++)
{
object child = array[i];
object mappedChild = MapAll(child, func);
if (mappedChild == null) return null;
if (mappedChild != child)
{
resultArray = (object[])array.Clone();
resultArray[i] = mappedChild;
for (i++; i < array.Length; i++)
{
child = array[i];
mappedChild = MapAll(child, func);
if (mappedChild == null) return null;
resultArray[i] = mappedChild;
}
}
}
result = resultArray;
}
return func(result);
}
#endregion
}
}
|
using System.Web.Http;
using AutoMapper;
using Conditions.Guards;
using Properties.Core.Interfaces;
using Properties.Models;
namespace Properties.Controllers
{
[RoutePrefix(
"api/landlords/{landlordReference:length(1,12)}/submittedproperties/{submittedPropertyReference:length(1,14)}/description"
)]
public class DescriptionController : ApiController
{
private readonly IDescriptionService _descriptionService;
public DescriptionController(IDescriptionService descriptionService)
{
Check.If(descriptionService).IsNotNull();
_descriptionService = descriptionService;
}
[HttpGet, Route("")]
public Description GetDescription(string landlordReference, string submittedPropertyReference)
{
return
Mapper.Map<Description>(_descriptionService.GenerateDescription(landlordReference,
submittedPropertyReference));
}
}
}
|
using EAN.GPD.Domain.Entities;
using EAN.GPD.Domain.Models;
using EAN.GPD.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace EAN.GPD.Server.Controllers.V1
{
[Route("v1/arvore")]
public class ArvoreController : BaseController<ArvoreModel, ArvoreEntity>
{
public ArvoreController(IHttpContextAccessor accessor,
IArvoreRepository arvoreRepository) : base(accessor, arvoreRepository) { }
}
}
|
using System;
using System.Collections.Generic;
using Tomelt.Environment.Configuration;
using Tomelt.Environment.Extensions.Models;
using Tomelt.Modules.Models;
namespace Tomelt.Modules.ViewModels {
public class FeaturesViewModel {
public IEnumerable<ModuleFeature> Features { get; set; }
public FeaturesBulkAction BulkAction { get; set; }
public Func<ExtensionDescriptor, bool> IsAllowed { get; set; }
}
public enum FeaturesBulkAction {
None,
Enable,
Disable,
Update,
Toggle
}
} |
//using System.Collections.Generic;
//using System.Linq;
//using UseFul.Uteis;
//using Welic.Dominio.Models.Departamento.Map;
//namespace UseFul.ClientApi.Dtos
//{
// public class DepartamentoDto: BaseDto<DepartamentoDto>
// {
// public int IdDepartamento { get; set; }
// public string Descricao { get; set; }
// public int IdEmpresa { get; set; }
// public EmpresaDto EmpresaDto { get; set; }
// public DepartamentoDto()
// {
// }
// public DepartamentoDto ConsultaDepartamentoPorId(int idDepartamento)
// {
// var departamento =
// Adaptador.AdaptadorGeneric<DepartamentoMap,DepartamentoDto>(Context.Departamento.FirstOrDefault(d => d.IdDepartamento == idDepartamento));
// if (departamento == null)
// {
// throw CustomErro.Erro("Departamento não encontrado pelo código informado.");
// }
// return departamento;
// }
// public List<DepartamentoDto> ConsultaDepartamentos()
// {
// return Adaptador.AdaptadorGeneric<DepartamentoMap, DepartamentoDto>(Context.Departamento.OrderBy(d => d.Descricao).ToList());
// }
// public int BuscaCodigoDepartamentoPorDescricao(string descricao)
// {
// var departamentoEncontrado =
// Context.Departamento.FirstOrDefault(d => d.Descricao == descricao);
// if (departamentoEncontrado != null)
// {
// return departamentoEncontrado.IdDepartamento;
// }
// throw CustomErro.Erro("Departamento não encontrado pela descrição.");
// }
// }
//}
|
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
/// <summary>
/// Provides access to configuration data
/// </summary>
public static class ConfigurationUtils
{
#region Properties
/// <summary>
/// Gets the paddle move units per second
/// </summary>
/// <value>paddle move units per second</value>
public static float PaddleMoveUnitsPerSecond => ConfigurationData.PaddleMoveUnitsPerSecond;
/// <summary>
/// Gets the impulse force to apply to the move the balls
/// </summary>
public static float BallImpulseForce => ConfigurationData.BallImpulseForce;
/// <summary>
/// Gets the lifetime balls
/// </summary>
public static float BallLifetime => ConfigurationData.BallLifetime;
/// <summary>
/// Gets minimum time for random spawn balls
/// </summary>
public static float MinSpawnTime => ConfigurationData.MinSpawnTime;
/// <summary>
/// Gets maximum time for random spawn balls
/// </summary>
public static float MaxSpawnTime => ConfigurationData.MaxSpawnTime;
/// <summary>
/// Gets how many points standard block is worth
/// </summary>
public static int CostStandardBlock => ConfigurationData.CostStandardBlock;
/// <summary>
/// Gets how many points bonus block is worth
/// </summary>
public static int CostBonusBlock => ConfigurationData.CostBonusBlock;
/// <summary>
/// Gets how many points pickup blocks is worth
/// </summary>
public static int CostPickupBlocks => ConfigurationData.CostPickupBlocks;
/// <summary>
/// Gets how many balls maybe per games;
/// </summary>
public static int NumberBalls => ConfigurationData.NumberBalls;
/// <summary>
/// Gets the probability that a standard block will be added to the level
/// </summary>
public static float StandardBlockProbability => ConfigurationData.StandardBlockProbability;
/// <summary>
/// Gets the probability that a bonus block will be added to the level
/// </summary>
public static float BonusBlockProbability => ConfigurationData.BonusBlockProbability;
/// <summary>
/// Gets the probability that a freezer block will be added to the level
/// </summary>
public static float FreezerBlockProbability => ConfigurationData.FreezerBlockProbability;
/// <summary>
/// Gets the probability that a speedup block will be added to the level
/// </summary>
public static float SpeedupBlockProbability => ConfigurationData.SpeedupBlockProbability;
/// <summary>
/// Gets the freezer effect duration
/// </summary>
public static float FreezerEffectDuration => ConfigurationData.FreezerEffectDuration;
/// <summary>
/// Gets the speedup effect duration
/// </summary>
public static float SpeedupEffectDuration => ConfigurationData.SpeedupEffectDuration;
/// <summary>
/// Gets the speedup factor increase
/// </summary>
public static float SpeedupFactor => ConfigurationData.SpeedupFactor;
#endregion
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BattleShots
{
public interface IBluetooth
{
void SetupBt();
List<string> GetKnownDevices();
void StartDiscoveringDevices();
void StopDiscoveringDevices();
void PairToDevice(string name, bool known);
void ReceivePair();
void EnableDiscoverable();
void ReadMessage();
void SendMessage(string message);
bool GetMaster();
void CancelReconnection();
string GetConnectedDeviceName();
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using AdminAPI.Models;
using AdminAPI.Utility;
namespace AdminAPI.TokenModels
{
public class TokenProviderMiddleware
{
private readonly RequestDelegate _next;
private readonly TokenProviderOptions _options;
private readonly JsonSerializerSettings _serializerSettings;
public TokenProviderMiddleware(
RequestDelegate next,
IOptions<TokenProviderOptions> options)
{
_next = next;
_options = options.Value;
ThrowIfInvalidOptions(_options);
_serializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
}
public Task Invoke(HttpContext context)
{
if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
{
return _next(context);
}
if (!context.Request.Method.Equals("POST")
|| !context.Request.HasFormContentType)
{
context.Response.StatusCode = 400;
return context.Response.WriteAsync("Bad request.");
}
return GenerateToken(context);
}
private async Task GenerateToken(HttpContext context)
{
try
{
string username = Convert.ToString(context.Request.Form["username"]);
string password = Convert.ToString(context.Request.Form["password"]);
string type = Convert.ToString(context.Request.Form["type"]);
// var identity = await _options.IdentityResolver(username, password);
using (var _context = new AdminDemoContext())
{
try
{
bool data = false;
int id = 0;
AdminLogins admindata = new AdminLogins();
if (type == "admin")
{
admindata = _context.AdminLogins.Where(x => x.Username == username && x.Password == password && x.IsActive == true).FirstOrDefault();
if (admindata != null)
{
data = true;
id = admindata.AdminId;
}
}
if (data != false)
{
var identity = Task.FromResult(new ClaimsIdentity(new GenericIdentity(username, "Token"), new Claim[] { }));
var now = DateTime.UtcNow;
var claims = new Claim[]
{
new Claim("type",type),
new Claim("id",id.ToString()),
new Claim(JwtRegisteredClaimNames.Sub, username),
new Claim(JwtRegisteredClaimNames.Jti, await _options.NonceGenerator()),
new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
};
// Create the JWT and write it to a string
var jwt = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
notBefore: now,
expires: now.Add(_options.Expiration),
signingCredentials: _options.SigningCredentials);
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
if (type == "admin")
{
var response = new
{
status = "success",
access_token = encodedJwt,
expires_in = (int)_options.Expiration.TotalSeconds,
firstname = admindata.FirstName,
lastname = admindata.LastName,
username = admindata.Username,
password = admindata.Password,
usertype = type
};
// Serialize and return the response
context.Response.ContentType = "application/json";
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings));
}
}
else
{
context.Response.StatusCode = 200;
var response = new
{
status = "error",
msg = "Invalid username or password."
};
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings));
return;
}
}
catch (Exception ex)
{
}
}
}
catch (Exception ex) {
throw ex;
}
}
private static void ThrowIfInvalidOptions(TokenProviderOptions options)
{
if (string.IsNullOrEmpty(options.Path))
{
throw new ArgumentNullException(nameof(TokenProviderOptions.Path));
}
if (string.IsNullOrEmpty(options.Issuer))
{
throw new ArgumentNullException(nameof(TokenProviderOptions.Issuer));
}
if (string.IsNullOrEmpty(options.Audience))
{
throw new ArgumentNullException(nameof(TokenProviderOptions.Audience));
}
if (options.Expiration == TimeSpan.Zero)
{
throw new ArgumentException("Must be a non-zero TimeSpan.", nameof(TokenProviderOptions.Expiration));
}
if (options.IdentityResolver == null)
{
throw new ArgumentNullException(nameof(TokenProviderOptions.IdentityResolver));
}
if (options.SigningCredentials == null)
{
throw new ArgumentNullException(nameof(TokenProviderOptions.SigningCredentials));
}
if (options.NonceGenerator == null)
{
throw new ArgumentNullException(nameof(TokenProviderOptions.NonceGenerator));
}
}
}
}
|
//
// Tutorial2.cs
//
// Public domain C# ISAM .NET example
//
// FairCom Corporation, 6300 West Sugar Creek Drive, Columbia, MO 65203 USA
//
// The goal of this tutorial is to introduce the most basic ISAM .NET API
// to accomplish creating and manipulating a table through the ctreeServer
//
// Functionally, this application will perform the following:
// 1. Create a database
// 2. Create 4 tables each with an index
// 3. Populate each table with a few records
// 4. Build a query utilizing the advantage of indexes
// 5. Output the results of the query
//
using System;
using FairCom.CtreeDb;
using FairCom.CtreeDb.ENUMS;
namespace Tutorial2
{
class Tutorial2
{
static CTSession MySession;
static CTTable tableCustOrdr;
static CTTable tableOrdrItem;
static CTTable tableItemMast;
static CTTable tableCustMast;
static CTRecord recordCustOrdr;
static CTRecord recordOrdrItem;
static CTRecord recordItemMast;
static CTRecord recordCustMast;
//
// main()
//
// The main() function implements the concept of "init, define, manage
// and you're done..."
//
[STAThread]
static void Main(string[] args)
{
Initialize();
Define();
Manage();
Done();
Console.WriteLine("\nPress <ENTER> key to exit . . .");
Console.ReadLine();
}
//
// Initialize()
//
// Perform the minimum requirement of logging onto the c-tree Server
//
static void Initialize()
{
Console.WriteLine("INIT");
try
{
// allocate the session object
MySession = new CTSession(SESSION_TYPE.CTREE_SESSION);
// allocate the table objects
tableCustOrdr = new CTTable(MySession);
tableOrdrItem = new CTTable(MySession);
tableItemMast = new CTTable(MySession);
tableCustMast = new CTTable(MySession);
// allocate the record objects
recordCustOrdr = new CTRecord(tableCustOrdr);
recordOrdrItem = new CTRecord(tableOrdrItem);
recordItemMast = new CTRecord(tableItemMast);
recordCustMast = new CTRecord(tableCustMast);
}
catch (CTException E)
{
Handle_Exception(E);
}
try
{
// connect to server
Console.WriteLine("\tLogon to server...");
MySession.Logon("FAIRCOMS", "ADMIN", "ADMIN");
}
catch (CTException E)
{
Handle_Exception(E);
}
}
//
// Define()
//
// Open the table, if it exists. Otherwise create and open the table
//
static void Define()
{
Console.WriteLine("DEFINE");
Create_CustomerMaster_Table();
Create_CustomerOrders_Table();
Create_OrderItems_Table();
Create_ItemMaster_Table();
}
//
// Manage()
//
// Populates table and perform a simple query
//
static void Manage()
{
int quantity;
double price, total;
string itemnumb, custnumb, ordrnumb, custname;
bool isOrderFound, isItemFound;
Console.WriteLine("MANAGE");
// populate the tables with data
Add_CustomerMaster_Records();
Add_CustomerOrders_Records();
Add_OrderItems_Records();
Add_ItemMaster_Records();
// perform a query:
// list customer name and total amount per order
// name total
// @@@@@@@@@@@@@ $xx.xx
// for each order in the CustomerOrders table
// fetch order number
// fetch customer number
// fetch name from CustomerMaster table based on customer number
// for each order item in OrderItems table
// fetch item quantity
// fetch item number
// fetch item price from ItemMaster table based on item number
// next
// next
Console.WriteLine("\n\tQuery Results");
try
{
// get the first order
isOrderFound = recordCustOrdr.First();
while (isOrderFound) // for each order in the CustomerOrders table
{
// fetch order number
ordrnumb = recordCustOrdr.GetFieldAsString(2);
// fetch customer number
custnumb = recordCustOrdr.GetFieldAsString(3);
// fetch name from CustomerMaster table based on customer number
recordCustMast.Clear();
recordCustMast.SetFieldAsString(0, custnumb);
if (!recordCustMast.Find(FIND_MODE.EQ))
continue; // not possible in our canned example
custname = recordCustMast.GetFieldAsString(4);
// fetch item price from OrderItems table
recordOrdrItem.Clear();
recordOrdrItem.SetFieldAsString(2, ordrnumb);
// define a recordset to scan only items applicable to this order
recordOrdrItem.RecordSetOn(6);
isItemFound = recordOrdrItem.First();
total = 0;
while (isItemFound) // for each order item in OrderItems table
{
// fetch item quantity
recordOrdrItem.GetFieldValue(1,out quantity);
// fetch item number
itemnumb = recordOrdrItem.GetFieldAsString(3);
// fetch item price from ItemMaster table based on item number
recordItemMast.Clear();
recordItemMast.SetFieldAsString(2, itemnumb);
recordItemMast.Find(FIND_MODE.EQ);
recordItemMast.GetFieldValue(1,out price);
// calculate order total
total += (price * quantity);
isItemFound = recordOrdrItem.Next();
}
recordOrdrItem.RecordSetOff();
// output data to stdout
Console.WriteLine("\t\t{0,-20}{1,-8}", custname, total);
// read next order
if (!recordCustOrdr.Next())
isOrderFound = false;
}
}
catch (CTException E)
{
Handle_Exception(E);
}
}
//
// Done()
//
// This function handles the housekeeping of closing, freeing,
// disconnecting and logging out of the database
//
static void Done()
{
Console.WriteLine("DONE");
try
{
// close tables
Console.WriteLine("\tClose tables...");
tableCustMast.Close();
tableCustOrdr.Close();
tableOrdrItem.Close();
tableItemMast.Close();
// logout
Console.WriteLine("\tLogout...");
MySession.Logout();
}
catch (CTException E)
{
Handle_Exception(E);
}
}
//
// Create_CustomerMaster_Table()
//
// Open table CustomerMaster, if it exists. Otherwise create it
// along with its indices and open it
//
static void Create_CustomerMaster_Table()
{
bool do_create = false;
// define table CustomerMaster
Console.WriteLine("\ttable CustomerMaster");
try
{
tableCustMast.Open("custmast", OPEN_MODE.NORMAL_OPEN);
}
catch (CTException)
{
// table does not exist
do_create = true;
}
if (do_create)
{
try
{
// define table fields
CTField field1 = tableCustMast.AddField("cm_custnumb", FIELD_TYPE.FSTRING, 4);
tableCustMast.AddField("cm_custzipc", FIELD_TYPE.FSTRING, 9);
tableCustMast.AddField("cm_custstat", FIELD_TYPE.FSTRING, 2);
tableCustMast.AddField("cm_custratg", FIELD_TYPE.FSTRING, 1);
tableCustMast.AddField("cm_custname", FIELD_TYPE.VSTRING, 47);
tableCustMast.AddField("cm_custaddr", FIELD_TYPE.VSTRING, 47);
tableCustMast.AddField("cm_custcity", FIELD_TYPE.VSTRING, 47);
// define index
CTIndex index1 = tableCustMast.AddIndex("cm_custnumb_idx", KEY_TYPE.FIXED_INDEX, false, false);
index1.AddSegment(field1, SEG_MODE.SCHSEG_SEG);
// create table
Console.WriteLine("\tCreate table...");
tableCustMast.Create("custmast", CREATE_MODE.NORMAL_CREATE);
// open table
Console.WriteLine("\tOpen table...");
tableCustMast.Open("custmast", OPEN_MODE.NORMAL_OPEN);
}
catch (CTException E)
{
Handle_Exception(E);
}
}
else
{
Check_Table_Mode(tableCustMast);
// confirm the index exists, if not then add the index
//
// this scenario arises out of the fact that this table was created in tutorial 1
// without indexes. The index is now created by the call to ctdbAlterTable
do_create = false;
try
{
tableCustMast.GetIndex("cm_custnumb_idx");
}
catch (CTException)
{
do_create = true;
}
if (do_create)
{
try
{
CTField field1 = tableCustMast.GetField("cm_custnumb");
CTIndex index1 = tableCustMast.AddIndex("cm_custnumb_idx", KEY_TYPE.FIXED_INDEX, false, false);
index1.AddSegment(field1, SEG_MODE.SCHSEG_SEG);
tableCustMast.Alter(ALTER_TABLE.NORMAL);
}
catch (CTException E)
{
Handle_Exception(E);
}
}
}
}
//
// Create_CustomerOrders_Table()
//
// Open table CustomerOrders, if it exists. Otherwise create it
// along with its indices and open it
//
static void Create_CustomerOrders_Table()
{
bool do_create = false;
// define table CustomerOrders
Console.WriteLine("\ttable CustomerOrders");
try
{
tableCustOrdr.Open("custordr", OPEN_MODE.NORMAL_OPEN);
}
catch (CTException)
{
// table does not exist
do_create = true;
}
if (do_create)
{
try
{
// define table fields
tableCustOrdr.AddField("co_ordrdate", FIELD_TYPE.DATE, 4);
tableCustOrdr.AddField("co_promdate", FIELD_TYPE.DATE, 4);
CTField field1 = tableCustOrdr.AddField("co_ordrnumb", FIELD_TYPE.FSTRING, 6);
CTField field2 = tableCustOrdr.AddField("co_custnumb", FIELD_TYPE.FSTRING, 4);
// define indices
CTIndex index1 = tableCustOrdr.AddIndex("co_ordrnumb_idx", KEY_TYPE.LEADING_INDEX, false, false);
index1.AddSegment(field1, SEG_MODE.SCHSEG_SEG);
CTIndex index2 = tableCustOrdr.AddIndex("co_custnumb_idx", KEY_TYPE.LEADING_INDEX, true, false);
index2.AddSegment(field2, SEG_MODE.SCHSEG_SEG);
// create table
Console.WriteLine("\tCreate table...");
tableCustOrdr.Create("custordr", CREATE_MODE.NORMAL_CREATE);
// open table
Console.WriteLine("\tOpen table...");
tableCustOrdr.Open("custordr", OPEN_MODE.NORMAL_OPEN);
}
catch (CTException E)
{
Handle_Exception(E);
}
}
else
Check_Table_Mode(tableCustOrdr);
}
//
// Create_OrderItems_Table()
//
// Open table OrderItems, if it exists. Otherwise create it
// along with its indices and open it
//
static void Create_OrderItems_Table()
{
bool do_create = false;
// define table OrderItems
Console.WriteLine("\ttable OrderItems");
try
{
tableOrdrItem.Open("ordritem", OPEN_MODE.NORMAL_OPEN);
}
catch (CTException)
{
// table does not exist
do_create = true;
}
if (do_create)
{
try
{
// define table fields
CTField field1 = tableOrdrItem.AddField("oi_sequnumb", FIELD_TYPE.INT2, 2);
tableOrdrItem.AddField("oi_quantity", FIELD_TYPE.INT2, 2);
CTField field2 = tableOrdrItem.AddField("oi_ordrnumb", FIELD_TYPE.FSTRING, 6);
CTField field3 = tableOrdrItem.AddField("oi_itemnumb", FIELD_TYPE.FSTRING, 5);
// define indices
CTIndex index1 = tableOrdrItem.AddIndex("oi_ordrnumb_idx", KEY_TYPE.LEADING_INDEX, false, false);
index1.AddSegment(field2, SEG_MODE.SCHSEG_SEG);
index1.AddSegment(field1, SEG_MODE.SCHSEG_SEG);
CTIndex index2 = tableOrdrItem.AddIndex("oi_itemnumb_idx", KEY_TYPE.LEADING_INDEX, true, false);
index2.AddSegment(field3, SEG_MODE.SCHSEG_SEG);
// create table
Console.WriteLine("\tCreate table...");
tableOrdrItem.Create("ordritem", CREATE_MODE.NORMAL_CREATE);
// open table
Console.WriteLine("\tOpen table...");
tableOrdrItem.Open("ordritem", OPEN_MODE.NORMAL_OPEN);
}
catch (CTException E)
{
Handle_Exception(E);
}
}
else
Check_Table_Mode(tableOrdrItem);
}
//
// Create_ItemMaster_Table()
//
// Open table ItemMaster, if it exists. Otherwise create it
// along with its indices and open it
//
static void Create_ItemMaster_Table()
{
bool do_create = false;
// define table ItemMaster
Console.WriteLine("\ttable ItemMaster");
try
{
tableItemMast.Open("itemmast", OPEN_MODE.NORMAL_OPEN);
}
catch (CTException)
{
// table does not exist
do_create = true;
}
if (do_create)
{
try
{
// define table fields
tableItemMast.AddField("im_itemwght", FIELD_TYPE.INT4, 4);
tableItemMast.AddField("im_itempric", FIELD_TYPE.MONEY, 4);
CTField field1 = tableItemMast.AddField("im_itemnumb", FIELD_TYPE.FSTRING, 5);
tableItemMast.AddField("im_itemdesc", FIELD_TYPE.VSTRING, 47);
// define indices
CTIndex index1 = tableItemMast.AddIndex("im_itemnumb_idx", KEY_TYPE.LEADING_INDEX, false, false);
index1.AddSegment(field1, SEG_MODE.SCHSEG_SEG);
// create table
Console.WriteLine("\tCreate table...");
tableItemMast.Create("itemmast", CREATE_MODE.NORMAL_CREATE);
// open table
Console.WriteLine("\tOpen table...");
tableItemMast.Open("itemmast", OPEN_MODE.NORMAL_OPEN);
}
catch (CTException E)
{
Handle_Exception(E);
}
}
else
Check_Table_Mode(tableItemMast);
}
//
// Check_Table_Mode()
//
// Check if existing table has transaction processing flag enabled.
// If a table is under transaction processing control, modify the
// table mode to disable transaction processing
//
static void Check_Table_Mode(CTTable table)
{
try
{
// get table create mode
CREATE_MODE mode = table.GetCreateMode();
// check if table is under transaction processing control
if ((mode & CREATE_MODE.TRNLOG_CREATE) != 0)
{
// change file mode to disable transaction processing
mode ^= CREATE_MODE.TRNLOG_CREATE;
table.UpdateCreateMode(mode);
}
}
catch (CTException E)
{
Handle_Exception(E);
}
}
//
// Add_CustomerMaster_Records()
//
// This function adds records to table CustomerMaster from an
// array of strings
//
public struct CUSTOMER_DATA
{
// struct members
public string number, zipcode, state, rating, name, address, city;
// struct constructor
public CUSTOMER_DATA(string number, string zipcode, string state, string rating, string name, string address, string city)
{
this.number = number;
this.zipcode = zipcode;
this.state = state;
this.rating = rating;
this.name = name;
this.address = address;
this.city = city;
}
};
static void Add_CustomerMaster_Records()
{
CUSTOMER_DATA[] data = new CUSTOMER_DATA[4];
data[0] = new CUSTOMER_DATA("1000", "92867", "CA", "1", "Bryan Williams", "2999 Regency", "Orange");
data[1] = new CUSTOMER_DATA("1001", "61434", "CT", "1", "Michael Jordan", "13 Main", "Harford");
data[2] = new CUSTOMER_DATA("1002", "73677", "GA", "1", "Joshua Brown", "4356 Cambridge", "Atlanta");
data[3] = new CUSTOMER_DATA("1003", "10034", "MO", "1", "Keyon Dooling", "19771 Park Avenue", "Columbia");
int nRecords = data.Length;
Delete_Records(recordCustMast);
Console.WriteLine("\tAdd records in table CustomerMaster...");
try
{
for (int i = 0; i < nRecords; i++)
{
recordCustMast.Clear();
// populate record buffer with data
recordCustMast.SetFieldAsString(0, data[i].number);
recordCustMast.SetFieldAsString(1, data[i].zipcode);
recordCustMast.SetFieldAsString(2, data[i].state);
recordCustMast.SetFieldAsString(3, data[i].rating);
recordCustMast.SetFieldAsString(4, data[i].name);
recordCustMast.SetFieldAsString(5, data[i].address);
recordCustMast.SetFieldAsString(6, data[i].city);
// add record
recordCustMast.Write();
}
}
catch(CTException E)
{
Handle_Exception(E);
}
}
//
// Add_CustomerOrders_Records()
//
// This function adds records to table CustomerOrders from an
// array of strings
//
public struct ORDER_DATA
{
// struct members
public string orderdate, promisedate, ordernum, customernum;
// struct constructor
public ORDER_DATA(string orderdate, string promisedate, string ordernum, string customernum)
{
this.orderdate = orderdate;
this.promisedate = promisedate;
this.ordernum = ordernum;
this.customernum = customernum;
}
};
static void Add_CustomerOrders_Records()
{
ORDER_DATA[] data = new ORDER_DATA[2];
data[0] = new ORDER_DATA("09/01/2002", "09/05/2002", "1", "1001");
data[1] = new ORDER_DATA("09/02/2002", "09/06/2002", "2", "1002");
int nRecords = data.Length;
CTDate orderdate = new CTDate();
CTDate promisedate = new CTDate();
Delete_Records(recordCustOrdr);
Console.WriteLine("\tAdd records in table CustomerOrders...");
try
{
for (int i = 0; i < nRecords; i++)
{
recordCustOrdr.Clear();
orderdate.StringToDate(data[i].orderdate, DATE_TYPE.MDCY_DATE);
promisedate.StringToDate(data[i].promisedate, DATE_TYPE.MDCY_DATE);
// populate record buffer with data
recordCustOrdr.SetFieldValue(0, orderdate);
recordCustOrdr.SetFieldValue(1, promisedate);
recordCustOrdr.SetFieldAsString(2, data[i].ordernum);
recordCustOrdr.SetFieldAsString(3, data[i].customernum);
// add record
recordCustOrdr.Write();
}
}
catch(CTException E)
{
Handle_Exception(E);
}
}
//
// Add_OrderItems_Records()
//
// This function adds records to table OrderItems from an
// array of strings
//
public struct ORDERITEM_DATA
{
// struct members
public int sequencenum, quantity;
public string ordernum, itemnum;
// struct constructor
public ORDERITEM_DATA(int sequencenum, int quantity, string ordernum, string itemnum)
{
this.sequencenum = sequencenum;
this.quantity = quantity;
this.ordernum = ordernum;
this.itemnum = itemnum;
}
};
static void Add_OrderItems_Records()
{
ORDERITEM_DATA[] data = new ORDERITEM_DATA[4];
data[0] = new ORDERITEM_DATA(1, 2, "1", "1");
data[1] = new ORDERITEM_DATA(2, 1, "1", "2");
data[2] = new ORDERITEM_DATA(3, 1, "1", "3");
data[3] = new ORDERITEM_DATA(1, 3, "2", "3");
int nRecords = data.Length;
Delete_Records(recordOrdrItem);
Console.WriteLine("\tAdd records in table OrderItems...");
try
{
for (int i = 0; i < nRecords; i++)
{
recordOrdrItem.Clear();
// populate record buffer with data
recordOrdrItem.SetFieldValue(0, data[i].sequencenum);
recordOrdrItem.SetFieldValue(1, data[i].quantity);
recordOrdrItem.SetFieldValue(2, data[i].ordernum);
recordOrdrItem.SetFieldValue(3, data[i].itemnum);
// add record
recordOrdrItem.Write();
}
}
catch(CTException E)
{
Handle_Exception(E);
}
}
//
// Add_ItemMaster_Records()
//
// This function adds records to table ItemMaster from an
// array of strings
//
public struct ITEM_DATA
{
// struct members
public int weight;
public CTMoney price;
public string itemnum, description;
// struct constructor
public ITEM_DATA(int weight, CTMoney price, string itemnum, string description)
{
this.weight = weight;
this.price = price;
this.itemnum = itemnum;
this.description = description;
}
};
static void Add_ItemMaster_Records()
{
ITEM_DATA[] data = new ITEM_DATA[4];
data[0] = new ITEM_DATA(10, (CTMoney)1995, "1", "Hammer");
data[1] = new ITEM_DATA(3, (CTMoney)999, "2", "Wrench");
data[2] = new ITEM_DATA(4, (CTMoney)1659, "3", "Saw");
data[3] = new ITEM_DATA(1, (CTMoney)398, "4", "Pliers");
int nRecords = data.Length;
Delete_Records(recordItemMast);
Console.WriteLine("\tAdd records in table ItemMaster...");
try
{
for (int i = 0; i < nRecords; i++)
{
recordItemMast.Clear();
// populate record buffer with data
recordItemMast.SetFieldValue(0, data[i].weight);
recordItemMast.SetFieldValue(1, data[i].price);
recordItemMast.SetFieldAsString(2, data[i].itemnum);
recordItemMast.SetFieldAsString(3, data[i].description);
// add record
recordItemMast.Write();
}
}
catch(CTException E)
{
Handle_Exception(E);
}
}
//
// Delete_Records()
//
// This function deletes all the records in the table
//
static void Delete_Records(CTRecord record)
{
bool found;
Console.WriteLine("\tDelete records...");
try
{
// read first record
found = record.First();
while (found) // while records are found
{
// delete record
record.Delete();
// read next record
found = record.Next();
}
}
catch (CTException E)
{
Handle_Exception(E);
}
}
//
// Handle_Exception()
//
// This function handles unexpected exceptions. It displays an error message
// allowing the user to acknowledge before terminating the application
//
static void Handle_Exception(CTException err)
{
Console.WriteLine("\nERROR: [{0}] - {1}", err.GetErrorCode(), err.GetErrorMsg());
Console.WriteLine("*** Execution aborted *** ");
Console.WriteLine("\nPress <ENTER> key to exit . . .");
Console.ReadLine();
Environment.Exit(1);
}
}
}
// end of Tutorial2.cs
|
using UnityEngine;
using System.Collections;
public class ConeOfViewController : MonoBehaviour {
public ConeOfViewRenderer leftCone;
public ConeOfViewRenderer rightCone;
public float innerGapHalfAngle = 0;
public float actualAngleRange { get; private set;}
bool registeredForEvents;
public static ConeOfViewController instance;
void Awake() {
instance = this;
registeredForEvents = false;
}
// Use this for initialization
void Start () {
RegisterForEvents ();
MaybeUpdateAngleRange ();
UpdateCones ();
}
void OnDestroy() {
UnregisterForEvents ();
}
void RegisterForEvents() {
BoostConfig.instance.BoostActive += new BoostConfig.BoostActiveEventHandler (OnBoostUsageChanged);
registeredForEvents = true;
}
void UnregisterForEvents() {
if (registeredForEvents) {
BoostConfig.instance.BoostActive -= new BoostConfig.BoostActiveEventHandler (OnBoostUsageChanged);
}
}
void OnBoostUsageChanged(BoostConfig.BoostType newType,
BoostConfig.BoostType oldType) {
if (MaybeUpdateAngleRange ()) {
UpdateCones ();
}
}
bool MaybeUpdateAngleRange() {
float newAngleRange;
if (BoostConfig.instance.activeBoost == BoostConfig.BoostType.BOOST_TYPE_GOOD_EYES) {
newAngleRange = TweakableParams.baseSwipeAngleRange *
TweakableParams.goodEyesAngleMultiplier;
} else {
newAngleRange = TweakableParams.baseSwipeAngleRange;
}
if (newAngleRange != actualAngleRange) {
actualAngleRange = newAngleRange;
return true;
} else {
return false;
}
}
void UpdateCones() {
leftCone.CreateMeshForAngleRange (innerGapHalfAngle, actualAngleRange/2);
rightCone.CreateMeshForAngleRange (-actualAngleRange/2, -innerGapHalfAngle);
}
}
|
using Konscious.Security.Cryptography;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
namespace thedailypost.Service
{
public static class UserServiceHelper
{
// Generates a random salt
public static byte[] CreateSalt()
{
var buffer = new byte[16];
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(buffer);
return buffer;
}
// Creates a hashed password with a salt generated from this class
public static byte[] HashPassword(string password, byte[] salt)
{
var argon2 = new Argon2id(Encoding.UTF8.GetBytes(password));
argon2.Salt = salt;
argon2.DegreeOfParallelism = 8; // 4 cores
argon2.Iterations = 4;
argon2.MemorySize = 1024 * 1024; // 1 GB
return argon2.GetBytes(16);
}
// Checks if the hash is correct (for logging in)
public static bool VerifyHash(string password, byte[] salt, byte[] hash) {
var hashedPass = HashPassword(password, salt);
return hash.SequenceEqual(hashedPass);
}
}
}
|
using Sentry.Extensibility;
using Sentry.Internal;
using Sentry.Internal.Extensions;
namespace Sentry.Protocol;
/// <summary>
/// Describes the application.
/// </summary>
/// <remarks>
/// As opposed to the runtime, this is the actual application that
/// was running and carries meta data about the current session.
/// </remarks>
/// <seealso href="https://develop.sentry.dev/sdk/event-payloads/contexts/"/>
public sealed class App : IJsonSerializable, ICloneable<App>, IUpdatable<App>
{
/// <summary>
/// Tells Sentry which type of context this is.
/// </summary>
public const string Type = "app";
/// <summary>
/// Version-independent application identifier, often a dotted bundle ID.
/// </summary>
public string? Identifier { get; set; }
/// <summary>
/// Formatted UTC timestamp when the application was started by the user.
/// </summary>
public DateTimeOffset? StartTime { get; set; }
/// <summary>
/// Application specific device identifier.
/// </summary>
public string? Hash { get; set; }
/// <summary>
/// String identifying the kind of build, e.g. testflight.
/// </summary>
public string? BuildType { get; set; }
/// <summary>
/// Human readable application name, as it appears on the platform.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// Human readable application version, as it appears on the platform.
/// </summary>
public string? Version { get; set; }
/// <summary>
/// Internal build identifier, as it appears on the platform.
/// </summary>
public string? Build { get; set; }
/// <summary>
/// Clones this instance.
/// </summary>
internal App Clone() => ((ICloneable<App>)this).Clone();
App ICloneable<App>.Clone()
=> new()
{
Identifier = Identifier,
StartTime = StartTime,
Hash = Hash,
BuildType = BuildType,
Name = Name,
Version = Version,
Build = Build
};
/// <summary>
/// Updates this instance with data from the properties in the <paramref name="source"/>,
/// unless there is already a value in the existing property.
/// </summary>
internal void UpdateFrom(App source) => ((IUpdatable<App>)this).UpdateFrom(source);
void IUpdatable.UpdateFrom(object source)
{
if (source is App app)
{
((IUpdatable<App>)this).UpdateFrom(app);
}
}
void IUpdatable<App>.UpdateFrom(App source)
{
Identifier ??= source.Identifier;
StartTime ??= source.StartTime;
Hash ??= source.Hash;
BuildType ??= source.BuildType;
Name ??= source.Name;
Version ??= source.Version;
Build ??= source.Build;
}
/// <inheritdoc />
public void WriteTo(Utf8JsonWriter writer, IDiagnosticLogger? _)
{
writer.WriteStartObject();
writer.WriteString("type", Type);
writer.WriteStringIfNotWhiteSpace("app_identifier", Identifier);
writer.WriteStringIfNotNull("app_start_time", StartTime);
writer.WriteStringIfNotWhiteSpace("device_app_hash", Hash);
writer.WriteStringIfNotWhiteSpace("build_type", BuildType);
writer.WriteStringIfNotWhiteSpace("app_name", Name);
writer.WriteStringIfNotWhiteSpace("app_version", Version);
writer.WriteStringIfNotWhiteSpace("app_build", Build);
writer.WriteEndObject();
}
/// <summary>
/// Parses from JSON.
/// </summary>
public static App FromJson(JsonElement json)
{
var identifier = json.GetPropertyOrNull("app_identifier")?.GetString();
var startTime = json.GetPropertyOrNull("app_start_time")?.GetDateTimeOffset();
var hash = json.GetPropertyOrNull("device_app_hash")?.GetString();
var buildType = json.GetPropertyOrNull("build_type")?.GetString();
var name = json.GetPropertyOrNull("app_name")?.GetString();
var version = json.GetPropertyOrNull("app_version")?.GetString();
var build = json.GetPropertyOrNull("app_build")?.GetString();
return new App
{
Identifier = identifier,
StartTime = startTime,
Hash = hash,
BuildType = buildType,
Name = name,
Version = version,
Build = build
};
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace FuelRadar.UI
{
public partial class SearchStartPage : ContentPage
{
public SearchStartPage(object dataContext)
{
this.BindingContext = dataContext;
this.InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using HTB.Database;
using HTB.Database.Views;
using HTB.v2.intranetx.routeplanter;
using HTBUtilities;
using log4net.Config;
namespace HTBRouteInfoLoader
{
class RouteInfoLoader
{
private static readonly RoutePlanerManager RpManager = new RoutePlanerManager(999, true, "99999");
private readonly int _initialMaxAddresses = 30;
private readonly int _subsequentAddresses = 10;
private readonly int _maximumMaxAddresses = 10000;
private readonly int _maximumRoadsPerThread = 1000;
private readonly int _sleepTime = 10000;
private readonly int _sleepTime2 = 100000;
private readonly int _skipTill = 2940;
private readonly int _maxAddresses = 30;
private readonly int _timeToWaitTillRoadLoadingAbort;
private readonly int _aussendienst = -1;
private readonly int _initializeSkipAfterThisManyRuns;
private readonly string _db2Schema;
private readonly int _runCounter;
private int _totCounter = 0;
private Stopwatch _stopwatch = new Stopwatch();
private RouteInfoLoader()
{
XmlConfigurator.Configure(new FileInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Log4Net.config")));
_initialMaxAddresses = Convert.ToInt32(ConfigurationManager.AppSettings["InitialMaxAddresses"]);
_subsequentAddresses = Convert.ToInt32(ConfigurationManager.AppSettings["SubsequentAddresses"]);
_maximumMaxAddresses = Convert.ToInt32(ConfigurationManager.AppSettings["MaximumMaxAddresses"]);
_maximumRoadsPerThread = Convert.ToInt32(ConfigurationManager.AppSettings["MaximumRoadsPerThread"]);
_sleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["SleepTime"]);
_sleepTime2 = Convert.ToInt32(ConfigurationManager.AppSettings["SleepTime2"]);
_skipTill = Convert.ToInt32(ConfigurationManager.AppSettings["SkipTill"]);
_aussendienst = Convert.ToInt32(ConfigurationManager.AppSettings["Aussendienst"]);
_initializeSkipAfterThisManyRuns = Convert.ToInt32(ConfigurationManager.AppSettings["InitializeSkipAfterThisManyRuns"]);
_timeToWaitTillRoadLoadingAbort = Convert.ToInt32(ConfigurationManager.AppSettings["TimeToWaitTillRoadLoadingAbort"]);
_db2Schema = ConfigurationManager.AppSettings["DB2Schema"];
RoutePlanerManager.TimeToSleepBetweenRefreshes = Convert.ToInt32(ConfigurationManager.AppSettings["RoutePlannerManager_TimeToSleepBetweenRefreshes"]);
_maxAddresses = _initialMaxAddresses;
_runCounter = 0;
_stopwatch.Start();
try
{
while (true)
{
LoadRouteInfo();
Thread.Sleep(_sleepTime2);
_maxAddresses += _subsequentAddresses;
if (_maxAddresses == _maximumMaxAddresses)
_maxAddresses = _initialMaxAddresses;
_runCounter++;
if (_runCounter >= _initializeSkipAfterThisManyRuns)
_skipTill = 0;
}
}
catch (Exception e)
{
Console.WriteLine("MAIN ERR: "+e.Message);
Console.WriteLine(e.StackTrace);
Console.ReadLine();
//restart program
// Process.Start("HTBRouteInfoLoader.exe");
// Process.GetCurrentProcess().Kill();
}
}
private void LoadRouteInfo()
{
RpManager.Clear();
var adList = GetAussendiestList();
int adCounter = 0;
foreach (var ad in adList)
{
var aktenList = HTBUtils.GetSqlRecords("SELECT * FROM qryAktenInt WHERE AktIntStatus = 1 AND AktIntSB = " + ad, typeof(qryAktenInt));
// if (_maxAddresses <= aktenList.Count)
// {
int crrCoutner = 0;
var toProcess = new List<qryAktenInt>();
foreach (qryAktenInt akt in aktenList)
{
toProcess.Add(akt);
if (crrCoutner >= _maxAddresses)
{
Console.WriteLine("Processing [AD: {0}] [AD Akten Processed: {1}] [Total: {2}] [AD Count: {3}] [AD Akten: {4}]", ad, adCounter, _totCounter, adList.Count, aktenList.Count);
RpManager.Clear();
try
{
if (_totCounter > _skipTill)
{
LoadAddresses(toProcess);
RpManager.LoadGeocodeAddresses(false, "HTBRouteInfoLoader.exe");
List<Road> allRoads = RpManager.GetRoads();
int roadCount = 0;
int totRoadCount = 0;
var roadsToProcess = new List<Road>();
foreach(Road r in allRoads)
{
totRoadCount++;
roadsToProcess.Add(r);
if (++roadCount % _maximumRoadsPerThread == 0)
{
Console.WriteLine("Loading Roads [Total: {0}] [Roads: {1} OF {2}]", _totCounter, totRoadCount, allRoads.Count);
RpManager.LoadDistances_NoRoutePlanner(_timeToWaitTillRoadLoadingAbort, _stopwatch, roadsToProcess, false, "HTBRouteInfoLoader.exe");
// Console.WriteLine("Saving Distances");
RpManager.SaveDistances();
// Console.WriteLine("Distances Saved");
roadsToProcess.Clear();
roadCount = 0;
// Thread.Sleep(_sleepTime); // just for debug
}
}
// Console.WriteLine("Loading Roads 2");
RpManager.LoadDistances_NoRoutePlanner(_timeToWaitTillRoadLoadingAbort, _stopwatch, roadsToProcess, false, "HTBRouteInfoLoader.exe");
// Console.WriteLine("Saving Distances 2");
RpManager.SaveDistances();
// Console.WriteLine("Distances Saved");
SetConfigValue("SkipTill", _totCounter.ToString());
}
toProcess.Clear();
Console.WriteLine("Done Iteration");
}
catch
{
toProcess.Clear();
}
try
{
Console.WriteLine("Sleeping: "+_sleepTime);
if (_totCounter > _skipTill)
Thread.Sleep(_sleepTime);
}
catch
{
}
crrCoutner = 0;
}
adCounter++;
crrCoutner++;
_totCounter++;
}
// }
// else
// {
// Console.WriteLine("Skiped AD: {0}", ad);
// }
adCounter = 0;
}
}
private void LoadAddresses(List<qryAktenInt> akten)
{
foreach (qryAktenInt akt in akten)
{
var address = new StringBuilder(HTBUtils.ReplaceStringAfter(HTBUtils.ReplaceStringAfter(akt.GegnerLastStrasse, " top ", ""), "/", ""));
address.Append(",");
address.Append(akt.GegnerLastZip);
address.Append(",");
address.Append(akt.GegnerLastOrt);
address.Append(",österreich");
RpManager.AddAddress(new AddressWithID(akt.AktIntID, address.ToString()));
}
}
private List<string> GetAussendiestList()
{
var users = HTBUtils.GetSqlRecords("SELECT * FROM tblUser WHERE UserStatus = 1 " + (_aussendienst > 0 ? "and UserId = " + _aussendienst : ""), typeof(tblUser));
return (from tblUser user in users select user.UserID.ToString()).ToList();
}
private void SetConfigValue(string name, string value)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = config.AppSettings.Settings;
// update SaveBeforeExit
settings[name].Value = value;
//save the file
config.Save(ConfigurationSaveMode.Modified);
//relaod the section you modified
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
}
static void Main(string[] args)
{
new RouteInfoLoader();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace MODEL.ViewModel
{
public partial class VIEW_MST_CATEGORY
{
public List<VIEW_MST_CATEGORY> children { get; set; }
[Required]
public new string CATE_CD { get; set; }
[Required(ErrorMessage="分类名称不能为空")]
public new string CATEGORY_NAME { get; set; }
[Required(ErrorMessage = "父分类不能为空")]
public new string PARENT_CD { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace CountrySS
{
class Country
{
private string name;
private Int64 population;
private float area;
private HashSet<string> cities;
private string[] arrays;
public Country(string name, int population, int area)
{
this.Name = name;
this.Population = population;
this.Area = area;
}
public Country(string name, int population, int area, params string[] cities)
: this(name, population, area)
{
this.Cities = new HashSet<string>(cities);
}
public string Name { get; set; }
public Int64 Population { get; set; }
public float Area { get; set; }
public HashSet<string> Cities { get; set; }
public override int GetHashCode()
{
return this.Name.GetHashCode() ^ this.Area.GetHashCode();
}
public override bool Equals(object obj)
{
Country tmpCountry = obj as Country;
if (tmpCountry == null)
{
return false;
}
if (this.Name == tmpCountry.Name)
{
return true;
}
return false;
}
public static bool operator ==(Country c1, Country c2)
{
return Equals(c1, c2);
}
public static bool operator !=(Country c1, Country c2)
{
return !Equals(c1, c2);
}
}
}
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Podemski.Musicorum.Interfaces.Entities;
namespace Podemski.Musicorum.Dao.Entities
{
public sealed class Artist : IArtist
{
public Artist()
{
Albums = Enumerable.Empty<IAlbum>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<IAlbum> Albums { get; set; }
public override string ToString() => Id.ToString();
//public override string ToString() => Name;
}
} |
using FootballTAL.Data;
using System;
namespace FootballTAL.BusinessLogic
{
public class CreateFootballClub
{
public FootballClubExtenions CreateClub(string[] fields)
{
try
{
return new FootballClubExtenions()
{
ClubRank = int.Parse(fields[0].Split('.')[0]),
ClubName = fields[0].Split('.')[1].Trim(),
P = int.Parse(fields[1]),
W = int.Parse(fields[2]),
L = int.Parse(fields[3]),
D = int.Parse(fields[4]),
F = int.Parse(fields[5]),
//field[6] is "-"
A = int.Parse(fields[7]),
Pts = int.Parse(fields[8])
};
}
catch(Exception)
{
return new FootballClubExtenions { ErrorFound = true };
}
}
}
}
|
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using Photon.Pun;
using Photon.Realtime;
using System.Collections;
public class GameModeManager : MonoBehaviourPunCallbacks
{
private const string FORTUNE = "myFortune";
private const string WIN_MESSAGE = "Congrats ! You won the game!";
private const string DRAW_MESSAGE = "Congrats ! You reached the end, it's a draw!";
public const string TIMER_TOGGLE_NAME = "Timer";
public const string SCORE_TOGGLE_NAME = "ScoreReach";
public const string STARTED_ALREADY = "startedAlready";
private const int TIME_LIMIT = 1;
private const int AMOUNT_REACH = 2;
private const float AMOUNT_LIMIT = 30000;
private const float AMOUNT_LIMIT_SINGLE = 20000;
private float THE_AMOUNT = 0;
private const int FINAL_SECONDS = 6;
private float TIMER_LIMIT = 900; //15 mins = 60 * 15
private float TIMER_END = 0;
private string winnerName;
private int mode,playerAmount;
private bool timerOn, started,amountGoal,finalSeconds, ticksOn;
private Room myRoom;
private Player myPlayer;
public AudioSource ClockTicks,winSound,loseSound;
public Toggle timeLimit, scoreLimit;
public GameObject MasterPanel, OtherPanel, display, charSelectionPanel, winPanel, losePanel, diceRollButton, bankManager,scoresPanel,line2Panel;
public PrefabSpawner thePrefabSpawner;
public StatePresetManager theStateManager;
public TMP_Text gameModeText,lostText,wonText,p1Score,p2Score,p3Score,p4Score;
public static bool checkFortune, playerNameTagOn, arrivedLate, disqualified;
// Start is called before the first frame update
// Update is called once per frame
private void Start()
{
myPlayer = PhotonNetwork.LocalPlayer;
myRoom = GameManager.myRoom;
playerAmount = myRoom.PlayerCount;
started =playerNameTagOn=arrivedLate=finalSeconds= false;
if (myRoom.CustomProperties[STARTED_ALREADY] != null)
{
if ((int)myRoom.CustomProperties[STARTED_ALREADY] == 1)
{
Debug.Log("Oh no i'm late");
LateSetUp();
}
}
}
private void Update()
{
if (GameManager.instance.gameCanStart && !started)
{
started = true;
if (myPlayer.IsMasterClient)
{
if (!photonView.IsMine)
{
photonView.TransferOwnership(myPlayer);
}
photonView.RPC("ActivateGameMode", RpcTarget.AllBuffered, mode);
}
}
else
{
if (timerOn)
{
if (TIMER_LIMIT > 0)
{
if(finalSeconds)
{
if(!ticksOn)
{
ClockTicks.Play();
ticksOn = true;
}
TIMER_END = TIMER_END + Time.deltaTime;
if (TIMER_END >= 0.5)
{
gameModeText.enabled = true;
}
if (TIMER_END >= 1)
{
gameModeText.enabled = false;
TIMER_END = 0;
}
}
TIMER_LIMIT -= Time.deltaTime;
DisplayTime(TIMER_LIMIT);
}
else
{
ClockTicks.Stop();
DeactivateRollButton();
gameModeText.text = "Done!";
string key = "Player" + myPlayer.ActorNumber + "Fortune";
if (myRoom.CustomProperties[key] == null)
{
float totalFortune = MoneyManager.PLAYER_FORTUNE + MoneyManager.PLAYER_SAVINGS;
SetRoomProperty(key,totalFortune);
}
if (myPlayer.IsMasterClient)
{
bool goodToGo = true;
foreach(Player p in PhotonNetwork.PlayerListOthers)
{
string theKey = "Player" + p.ActorNumber + "Fortune";
if(myRoom.CustomProperties[theKey] == null)
{
goodToGo = false;
continue;
}
}
if (goodToGo)
{
if (PhotonNetwork.PlayerListOthers.Length > 0)
{
CheckWinner();
}
else
{
EndGameMessage();
}
timerOn = false;
}
}
else
{
timerOn = false;
}
}
}
else
{
if (amountGoal)
{
if (checkFortune)
{
checkFortune = false;
if ((MoneyManager.PLAYER_FORTUNE + MoneyManager.PLAYER_SAVINGS) > THE_AMOUNT)
{
amountGoal = false;
if (!photonView.IsMine)
{
photonView.TransferOwnership(myPlayer);
}
winnerName = myPlayer.NickName;
photonView.RPC("WinnerPanelActivation", RpcTarget.AllBuffered, winnerName);
//you won the game
}
}
}
}
}
if(disqualified)
{
disqualified = false;
if (!photonView.IsMine)
{
photonView.TransferOwnership(PhotonNetwork.LocalPlayer);
}
string winnerName = PhotonNetwork.PlayerListOthers[0].NickName;
photonView.RPC("WinnerPanelActivationAfterDQ", RpcTarget.AllBuffered, winnerName);
}
}
//this is for master player only
public void ConfirmGameMode()
{
SetRoomProperty(STARTED_ALREADY, 1);
if(timeLimit.isOn)
{
mode = TIME_LIMIT;
}
else if(scoreLimit.isOn)
{
mode = AMOUNT_REACH;
}
if(!photonView.IsMine)
{
photonView.TransferOwnership(myPlayer);
}
photonView.RPC("GoToCharSelect", RpcTarget.AllBuffered);
int temp = UnityEngine.Random.Range(0, PhotonNetwork.PlayerList.Length);
photonView.RPC("SetIndPlayerToPlay", RpcTarget.AllBuffered, temp);
}
[PunRPC]
private void GoToCharSelect()
{
if(PhotonNetwork.LocalPlayer.IsMasterClient)
{
PhotonNetwork.CurrentRoom.IsOpen = false;//we close the room to anyone else trying to join it when master client chose the game mode.
MasterPanel.SetActive(false);
}
else
{
OtherPanel.SetActive(false);
}
thePrefabSpawner.enabled = true;
theStateManager.enabled = true;
charSelectionPanel.SetActive(true);
display.SetActive(true);
bankManager.SetActive(true);
playerNameTagOn = true;
}
public void LateSetUp()
{
if (!photonView.IsMine)
{
photonView.TransferOwnership(myPlayer);
}
photonView.RPC("GivePlayerIndToPlay", RpcTarget.AllBuffered);
Debug.Log("player ind to play :" + GameManager.playerIndexToPlay);
OtherPanel.SetActive(false);
thePrefabSpawner.enabled = true;
theStateManager.enabled = true;
charSelectionPanel.SetActive(true);
display.SetActive(true);
bankManager.SetActive(true);
playerNameTagOn = true;
}
private void DisplayTime(float timeToDisplay)
{
float minutes = Mathf.FloorToInt(timeToDisplay / 60);
float seconds = Mathf.FloorToInt(timeToDisplay % 60);
gameModeText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
if(timeToDisplay<FINAL_SECONDS && !finalSeconds)
{
finalSeconds = true;
gameModeText.color = new Color(255, 0, 0, 255);
}
}
private void CheckWinner()
{
float winnerFortune = MoneyManager.PLAYER_FORTUNE + MoneyManager.PLAYER_SAVINGS;
winnerName = myPlayer.NickName;
int draw = 0;
foreach(Player p in PhotonNetwork.PlayerListOthers)
{
string key = "Player" + p.ActorNumber + "Fortune";
if((float)myRoom.CustomProperties[key]>winnerFortune)
{
winnerFortune = (float)myRoom.CustomProperties[key];
winnerName = p.NickName;
}
else
{
draw++;
}
}
if(draw.Equals(PhotonNetwork.PlayerListOthers.Length))
{
winnerName = "draw";
}
if (!photonView.IsMine)
{
photonView.TransferOwnership(myPlayer);
}
photonView.RPC("WinnerPanelActivation", RpcTarget.AllBuffered, winnerName);
}
private void EndGameMessage()
{
winnerName = myPlayer.NickName;
DeactivateRollButton();
DisplayWinPannel();
winPanel.SetActive(true);
scoresPanel.SetActive(true);
ShowScores();
winSound.Play();
wonText.text = "You reached the end of the game, congrats!";
}
[PunRPC]
private void ActivateGameMode(int theMode)
{
switch(theMode)
{
case TIME_LIMIT:
timerOn = true;
DisplayTime(TIMER_LIMIT);
break;
case AMOUNT_REACH:
amountGoal = true;
if (PhotonNetwork.PlayerListOthers.Length>0)
{
THE_AMOUNT = AMOUNT_LIMIT;
}
else
{
THE_AMOUNT = AMOUNT_LIMIT_SINGLE;
}
gameModeText.text = "Get a fortune of " +THE_AMOUNT.ToString()+ " to win!";
break;
}
}
[PunRPC]
private void WinnerPanelActivation(string name)
{
ChangeStateTime(false);
DeactivateRollButton();
if(name.Equals(myPlayer.NickName))
{
DisplayWinPannel();
}
else if (name.Equals("draw"))
{
DisplayDrawPanel();
}
else
{
DisplayLosePannel(name);
}
}
[PunRPC]
private float GetPlayerFortune(string name)
{
float theFortune = 0;
if (name.Equals(myPlayer.NickName))
{
theFortune = MoneyManager.PLAYER_FORTUNE;
}
return theFortune;
}
[PunRPC]
private void WinnerPanelActivationAfterDQ(string name)
{
DeactivateRollButton();
if (name.Equals(myPlayer.NickName))
{
Exit.playerWasDQ = true;
DisplayWinPannel();
}
else
{
Exit.exitAfterDQ = true;
}
}
private void DeactivateRollButton()
{
if (diceRollButton.activeSelf)
{
diceRollButton.SetActive(false);
}
}
private void DisplayDrawPanel()
{
winPanel.SetActive(true);
scoresPanel.SetActive(true);
ShowScores();
winSound.Play();
wonText.text = DRAW_MESSAGE;
}
private void DisplayWinPannel()
{
winPanel.SetActive(true);
scoresPanel.SetActive(true);
ShowScores();
winSound.Play();
wonText.text = WIN_MESSAGE;
}
private void ShowScores()
{
switch(myRoom.PlayerCount)
{
case 1:
line2Panel.SetActive(false);
p2Score.gameObject.SetActive(false);
break;
case 2:
line2Panel.SetActive(false);
break;
case 3:
p4Score.gameObject.SetActive(false);
break;
}
foreach (Player p in PhotonNetwork.PlayerList)
{
if (p.ActorNumber == 1)
{
float total = MoneyManager.PLAYER_FORTUNE + MoneyManager.PLAYER_SAVINGS;
p1Score.text = "Your score:\n" + total.ToString();
}
else
{
string key = "Player" + p.ActorNumber + "Fortune";
float total = (float)myRoom.CustomProperties[key];
if (p.ActorNumber == 2)
{
p2Score.text = "P2 score:\n" + total.ToString();
}
else if (p.ActorNumber == 3)
{
p3Score.text = "P3 score:\n" + total.ToString();
}
else if (p.ActorNumber == 4)
{
p4Score.text = "Your score:\n" + total.ToString();
}
}
}
}
private void DisplayLosePannel(string theWinner)
{
losePanel.SetActive(true);
scoresPanel.SetActive(true);
ShowScores();
loseSound.Play();
lostText.text = $"Sorry but {theWinner} won this game... Your time will come soon!";
}
private void SetRoomProperty(string hashKey, float value)//general room properties
{
if (myRoom.CustomProperties[hashKey] == null)
{
myRoom.CustomProperties.Add(hashKey, value);
}
else
{
myRoom.CustomProperties[hashKey] = value;
}
myRoom.SetCustomProperties(myRoom.CustomProperties);
while(myRoom.CustomProperties[hashKey] == null)
{
Debug.Log("Waiting");
}
}
private void SetRoomProperty(string hashKey, int value)//general room properties
{
if (myRoom.CustomProperties[hashKey] == null)
{
myRoom.CustomProperties.Add(hashKey, value);
}
else
{
myRoom.CustomProperties[hashKey] = value;
}
myRoom.SetCustomProperties(myRoom.CustomProperties);
while (myRoom.CustomProperties[hashKey] == null)
{
Debug.Log("Waiting");
}
}
public void ChangeStateTime(bool on)
{
if(on)
{
Time.timeScale = 1;
}
else
{
Time.timeScale = 0;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class HeartScript : MonoBehaviour {
private float timeBetweenBeats = 1.0f;
private float timerToBeat = 0.0f;
public GameObject blood;
bool playingBeatAnimation = false;
public Animator anim = null;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
CountdownToBeat();
}
void CountdownToBeat ()
{
if ( !playingBeatAnimation )
{
timerToBeat += Time.deltaTime;
if ( timerToBeat > timeBetweenBeats )
{
anim.SetInteger("State", 1);
playingBeatAnimation = true;
timerToBeat = 0.0f;
}
}
if( anim.speed > 10)
{
blood.SetActive(true);
Destroy(gameObject);
}
}
internal void ColidedWithBacteria()
{
if ( timeBetweenBeats > 0.0f )
{
timeBetweenBeats -= 0.1f;
}
anim.speed += 0.1f;
}
internal void DoneBeating()
{
anim.SetInteger("State", 0);
playingBeatAnimation = false;
}
}
|
using fNbt;
/// <summary>
/// Cell Behaviors should implement this if they wish to save extra data.
/// </summary>
public interface IHasData {
void writeToNbt(NbtCompound tag);
void readFromNbt(NbtCompound tag);
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class BaseQuestKillRequirement
{
public int enemyID;
public int quantity;
[ReadOnly] public int targetsKilled;
}
|
/***********************************************************************
* Module: PlacementInRoomController.cs
* Author: Dragana Carapic
* Purpose: Definition of the Class Controller.Examination&Placement&DrugController.PlacementInRoomController
***********************************************************************/
using Model.Doctor;
using Service.PlacementInARoomAndRenovationPeriod;
using System;
using System.Collections.Generic;
namespace Controller.PlacementInARoomAndRenovationPeriod
{
public class PlacementInSickRoomController
{
private PlacementInSickRoomService placementInSickRoomService = new PlacementInSickRoomService();
public int getLastId()
{
return placementInSickRoomService.getLastId();
}
public PlacemetnInARoom PlaceInRoom(PlacemetnInARoom placementInRoom)
{
// TODO: implement
return placementInSickRoomService.PlaceInRoom(placementInRoom);
}
public PlacemetnInARoom EditPlacement(PlacemetnInARoom placementInRoom)
{
// TODO: implement
return placementInSickRoomService.EditPlacement(placementInRoom);
}
public bool DeletePlacement(int idExamination)
{
// TODO: implement
return placementInSickRoomService.DeletePlacement(idExamination);
}
public List<PlacemetnInARoom> ViewAllPlacements()
{
// TODO: implement
return placementInSickRoomService.ViewAllPlacements();
}
public List<PlacemetnInARoom> ViewRoomPlacements(int roomNumber, DateTime beginDate, DateTime endDate)
{
// TODO: implement
return placementInSickRoomService.ViewRoomPlacements(roomNumber, beginDate, endDate);
}
public List<PlacemetnInARoom> ViewPatientPlacements(string jmbg)
{
return placementInSickRoomService.ViewPatientPlacements(jmbg);
}
public bool DeletePatientPlacements(string jmbg)
{
return placementInSickRoomService.DeletePatientPlacements(jmbg);
}
public bool DeleteRoomPlacements(int number)
{
return placementInSickRoomService.DeleteRoomPlacements(number);
}
}
} |
using System;
using System.DrawingCore;
namespace OOP_LAB_3.Model
{
public class Ring : UnFilledRing
{
public Ring(float radiusSmall, float radiusBig, Point startPoint, Graphics context) : base(radiusSmall, radiusBig, startPoint, context)
{
}
public override string Type => "filled ring";
public override void Draw()
{
base.Draw();
for (double i = 0; i < 1000;i+=1)
{
for (double j = 0; j < 700;j+=1)
{
if (Math.Pow(i-StartPoint.X,2) + Math.Pow(j-StartPoint.Y,2) > Math.Pow(CircleSmall.Radius,2) && Math.Pow(i-StartPoint.X, 2) + Math.Pow(j-StartPoint.Y, 2) < Math.Pow(CircleBig.Radius, 2))
Context.DrawRectangle(Pens.Black, i.ToFloat(), j.ToFloat(), 1, 1);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GDS.Entity
{
public class BackRoleMenuBind : ModelBase
{
public int MenuId { get; set; }
public int RoleId { get; set; }
public int OperationRight { get; set; } //操作权限
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntVenta
{
public class Venta
{
public int Id { get; set; }
public int IdCliente { get; set; }
public int IdUsuario { get; set; }
public int IdCaja { get; set; }
public DateTime FechaVenta { get; set; }
public string Cliente { get; set; }
public string Folio { get; set; }
public string Comprobante { get; set; }
public decimal MontoTotal { get; set; }
public decimal Saldo { get; set; }
public string FormaPago { get; set; }
public string EstadoPago { get; set; }
public string FechaLiquidacion { get; set; }
public string Accion { get; set; }
public decimal TipoPago { get; set; }
public string ReferenciaTarjeta { get; set; }
public decimal Vuelto { get; set; }
public decimal Efectivo { get; set; }
}
}
|
using Alabo.AutoConfigs.Repositories;
using Alabo.AutoConfigs.Services;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Entities;
using Alabo.Domains.Enums;
using Alabo.Domains.Services;
using Alabo.Extensions;
using Alabo.Framework.Basic.Grades.Domain.Configs;
using Alabo.Framework.Basic.Grades.Dtos;
using Alabo.Framework.Core.Enums.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Alabo.Framework.Basic.Grades.Domain.Services {
public class GradeService : ServiceBase, IGradeService {
public GradeService(IUnitOfWork unitOfWork) : base(unitOfWork) {
}
public UserGradeConfig DefaultUserGrade {
get {
var grades = GetUserGradeList();
if (grades != null) {
return grades.FirstOrDefault(r => r.IsDefault);
}
var gradeConfig = new UserGradeConfig();
gradeConfig.SetDefault();
return new UserGradeConfig();
}
}
public UserGradeConfig GetGrade(Guid gradeId) {
var userGrades = GetUserGradeList();
var grade = userGrades.FirstOrDefault(e => e.Id == gradeId);
if (grade == null) {
grade = new UserGradeConfig();
}
return grade;
}
public IList<UserGradeConfig> GetUserGradeList() {
var userGrades = Resolve<IAlaboAutoConfigService>()
.GetList<UserGradeConfig>(r => r.Status == Status.Normal);
if (userGrades.Count == 0) {
var userType = Resolve<IAlaboAutoConfigService>().GetList<UserTypeConfig>()
.FirstOrDefault(r => r.TypeClass == UserTypeEnum.Member);
var gradeConfig = new UserGradeConfig();
if (userType != null) {
gradeConfig.Id = userType.Id;
}
gradeConfig.SetDefault();
userGrades = Resolve<IAlaboAutoConfigService>()
.GetList<UserGradeConfig>(r => r.Status == Status.Normal);
}
return userGrades;
}
/// <summary>
/// 获取所有等级Key
/// </summary>
/// <param name="key"></param>
public List<BaseGradeConfig> GetGradeListByKey(string key) {
var config = Resolve<IAlaboAutoConfigService>().GetConfig(key);
var t = new BaseGradeConfig();
var configlist = new List<BaseGradeConfig>();
if (config != null) {
if (config.Value != null) {
configlist = config.Value.Deserialize(t);
}
}
return configlist;
}
/// <summary>
/// 根据用户类型Id,获取用户类型所有的等级
/// </summary>
/// <param name="guid"></param>
public List<BaseGradeConfig> GetGradeListByGuid(Guid guid) {
var configList = Repository<IAutoConfigRepository>().GetList(e => e.Type.Contains("GradeConfig"));
var baseGradeConfigs = new List<BaseGradeConfig>();
configList.Foreach(r => { baseGradeConfigs.AddRange(r.Value.Deserialize(new BaseGradeConfig())); });
var userTypeGrades = baseGradeConfigs.Where(r => r.UserTypeId == guid);
return userTypeGrades.ToList();
}
/// <summary>
/// 根据用户类型Id和等级Id获取用户类型等级
/// </summary>
/// <param name="userTypeId">用户类型Id></param>
/// <param name="gradeId">等级Id</param>
public BaseGradeConfig GetGradeByUserTypeIdAndGradeId(Guid userTypeId, Guid gradeId) {
var grades = GetGradeListByGuid(userTypeId);
var grade = grades?.FirstOrDefault(r => r.Id == gradeId);
return grade;
}
public ServiceResult UpdateUserGrade(UserGradeInput userGradeInput) {
//TODO 2019年9月22日 重构注释
//return Resolve<IUpgradeRecordService>()
// .ChangeUserGrade(userGradeInput.UserId, userGradeInput.GradeId, userGradeInput.Type);
return null;
}
public dynamic GetGrade(Guid userTypeId, Guid gradeId) {
throw new NotImplementedException();
}
}
} |
using Xamarin.Forms;
namespace ObservableTune.Views
{
public partial class ObsList2Page : ContentPage
{
public ObsList2Page()
{
InitializeComponent();
}
}
}
|
using jaytwo.Common.Extensions;
using jaytwo.Common.Http;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace jaytwo.Common.Test.Http.UrlHelperTests
{
public static class SetSchemeTests
{
private static IEnumerable<TestCaseData> UrlHelper_SetUriScheme_TestCases()
{
yield return new TestCaseData(null, "http").Throws(typeof(ArgumentNullException));
yield return new TestCaseData("http://www.google.com", null).Throws(typeof(ArgumentNullException));
yield return new TestCaseData("http://www.google.com", "").Throws(typeof(ArgumentException));
yield return new TestCaseData("../some/path", "https").Throws(typeof(InvalidOperationException));
yield return new TestCaseData("http://www.google.com", "https").Returns("https://www.google.com/");
yield return new TestCaseData("https://www.google.com", "ftp").Returns("ftp://www.google.com/");
yield return new TestCaseData("https://www.google.com:123", "ftp").Returns("ftp://www.google.com:123/");
}
[Test]
[TestCaseSource("UrlHelper_SetUriScheme_TestCases")]
public static string UrlHelper_SetUriScheme(string url, string newScheme)
{
var uri = TestUtility.GetUriFromString(url);
return UrlHelper.SetUriScheme(uri, newScheme).ToString();
}
[Test]
[TestCaseSource("UrlHelper_SetUriScheme_TestCases")]
public static string UrlHelper_SetUrlScheme(string url, string newScheme)
{
return UrlHelper.SetUrlScheme(url, newScheme);
}
[Test]
[TestCaseSource("UrlHelper_SetUriScheme_TestCases")]
public static string HttpExtensionMethods_WithScheme(string url, string newScheme)
{
var uri = TestUtility.GetUriFromString(url);
return uri.WithScheme(newScheme).ToString();
}
}
}
|
using Framework.Core.Common;
using Tests.Data.Van.Input;
using OpenQA.Selenium;
namespace Tests.Pages.Van.Main.VirtualPhoneBankPages.VirtualPhoneBankDetailsPageComponents
{
public class SkippingVpbDetailsPageComponent : VirtualPhoneBankDetailsPageComponent
{
private readonly Driver _driver;
#region Element Declarations
public IWebElement AllowUsersToSkipContactsAndHouseholdsCheckbox { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemSkipContactOption_VANInputItemDetailsItemSkipContactOption_SkipContactOption_0")); } }
public IWebElement ExcludeAnyoneWhoHasEarlyVotedOrAbsenteeVotedCheckbox { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemIsExcludeEarlyVote_VANInputItemDetailsItemIsExcludeEarlyVote_IsExcludeEarlyVote_0")); } }
public IWebElement ExcludeAnyoneWhoHasVotedOnElectionDayCheckbox { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VANDetailsItemIsExcludeGOTV_VANInputItemDetailsItemIsExcludeGOTV_IsExcludeGOTV_0")); } }
#endregion
public SkippingVpbDetailsPageComponent(Driver driver)
{
_driver = driver;
}
public override void SetFields(VirtualPhoneBank vpb)
{
_driver.CheckOrUncheck(AllowUsersToSkipContactsAndHouseholdsCheckbox, vpb.AllowUserstoSkipContactsAndHouseholds);
_driver.CheckOrUncheck(ExcludeAnyoneWhoHasEarlyVotedOrAbsenteeVotedCheckbox, vpb.ExcludeAnyoneWhoHasEarlyOrAbsenteeVoted);
_driver.CheckOrUncheck(ExcludeAnyoneWhoHasVotedOnElectionDayCheckbox, vpb.ExcludeAnyoneWhoHasVotedOnElectionDay);
}
public override bool Validate(VirtualPhoneBank vpb)
{
var errorCount = 0;
if (AllowUsersToSkipContactsAndHouseholdsCheckbox.Selected != vpb.AllowUserstoSkipContactsAndHouseholds)
{
errorCount++;
WriteVirtualPhoneBankValidationToConsole(AllowUsersToSkipContactsAndHouseholdsCheckbox,
vpb.AllowUserstoSkipContactsAndHouseholds.ToString(),
AllowUsersToSkipContactsAndHouseholdsCheckbox.Selected.ToString());
}
if (ExcludeAnyoneWhoHasEarlyVotedOrAbsenteeVotedCheckbox.Selected != vpb.ExcludeAnyoneWhoHasEarlyOrAbsenteeVoted)
{
errorCount++;
WriteVirtualPhoneBankValidationToConsole(ExcludeAnyoneWhoHasEarlyVotedOrAbsenteeVotedCheckbox,
vpb.ExcludeAnyoneWhoHasEarlyOrAbsenteeVoted.ToString(),
ExcludeAnyoneWhoHasEarlyVotedOrAbsenteeVotedCheckbox.Selected.ToString());
}
if (ExcludeAnyoneWhoHasVotedOnElectionDayCheckbox.Selected != vpb.ExcludeAnyoneWhoHasVotedOnElectionDay)
{
errorCount++;
WriteVirtualPhoneBankValidationToConsole(ExcludeAnyoneWhoHasVotedOnElectionDayCheckbox,
vpb.ExcludeAnyoneWhoHasVotedOnElectionDay.ToString(),
ExcludeAnyoneWhoHasVotedOnElectionDayCheckbox.Selected.ToString());
}
return errorCount < 1;
}
}
}
|
namespace BettingSystem.Application.Competitions.Teams.Queries.Details
{
using Common.Mapping;
using Domain.Competitions.Models.Teams;
public class TeamDetailsResponseModel : IMapFrom<Team>
{
public int Id { get; private set; }
public string Name { get; private set; } = default!;
public int Points { get; private set; }
}
}
|
using ApartmentApps.Api.Modules;
using ApartmentApps.Api.Services;
using ApartmentApps.Api.ViewModels;
using ApartmentApps.Data;
namespace ApartmentApps.Api
{
public class IncidentReportFormMapper : BaseMapper<IncidentReport, IncidentReportFormModel>
{
private readonly IBlobStorageService _blobStorageService;
public IMapper<ApplicationUser, UserBindingModel> UserMapper { get; set; }
public IncidentReportFormMapper(IMapper<ApplicationUser, UserBindingModel> userMapper,
IBlobStorageService blobStorageService, IUserContext userContext, IModuleHelper helper) : base(userContext, helper)
{
_blobStorageService = blobStorageService;
UserMapper = userMapper;
}
public override void ToModel(IncidentReportFormModel viewModel, IncidentReport model)
{
model.Comments = viewModel.Comments;
model.IncidentType = viewModel.ReportType;
model.UnitId = viewModel.UnitId;
}
public override void ToViewModel(IncidentReport model, IncidentReportFormModel viewModel)
{
viewModel.Comments = model.Comments;
viewModel.ReportType = model.IncidentType;
viewModel.UnitId = model.UnitId ?? 0;
viewModel.Id = model.Id.ToString();
}
}
} |
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace VEE.Models
{
// Puede agregar datos del perfil del usuario agregando más propiedades a la clase ApplicationUser. Para más información, visite http://go.microsoft.com/fwlink/?LinkID=317594.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Tenga en cuenta que el valor de authenticationType debe coincidir con el definido en CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Agregar aquí notificaciones personalizadas de usuario
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public System.Data.Entity.DbSet<VEE.Models.BasedeDatos.Grado> Gradoes { get; set; }
public System.Data.Entity.DbSet<VEE.Models.BasedeDatos.Escuela> Escuelas { get; set; }
public System.Data.Entity.DbSet<VEE.Models.BasedeDatos.Alumno> Alumnoes { get; set; }
public System.Data.Entity.DbSet<VEE.Models.BasedeDatos.Planilla> Planillas { get; set; }
public System.Data.Entity.DbSet<VEE.Models.BasedeDatos.CargoPlanilla> CargoPlanillas { get; set; }
public System.Data.Entity.DbSet<VEE.Models.BasedeDatos.DetallePlanilla> DetallePlanillas { get; set; }
public System.Data.Entity.DbSet<VEE.Models.BasedeDatos.Sufragio> Sufragios { get; set; }
public System.Data.Entity.DbSet<VEE.Models.BasedeDatos.Resultado> Resultadoes { get; set; }
}
} |
using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Stolons.Models;
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Hosting;
using System.Security.Claims;
using Microsoft.AspNet.Http;
using System.Collections.Generic;
using System.IO;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using Stolons.ViewModels.ProductsManagement;
using Microsoft.AspNet.Authorization;
using System.Drawing;
namespace Stolons.Controllers
{
public class ProductsManagementController : Controller
{
private ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private IHostingEnvironment _environment;
public ProductsManagementController(ApplicationDbContext context, UserManager<ApplicationUser> userManager, IHostingEnvironment environment)
{
_userManager = userManager;
_environment = environment;
_context = context;
}
// GET: ProductsManagement
[Authorize(Roles = Configurations.UserType_Producer)]
public async Task<IActionResult> Index()
{
var appUser = await GetCurrentUserAsync();
var products = _context.Products.Include(m => m.Familly).Include(m=>m.Familly.Type).Where(x => x.Producer.Email == appUser.Email).ToList();
return View(products);
}
[Authorize(Roles = Configurations.UserType_Producer)]
[HttpGet, ActionName("ProducerProducts"), Route("api/producerProducts")]
public string JsonProducerProducts()
{
var appUser = GetCurrentUserSync();
List<ProductViewModel> vmProducts = new List<ProductViewModel>();
var products = _context.Products.Include(m => m.Familly).Include(m=>m.Familly.Type).Where(x => x.Producer.Email == appUser.Email).ToList();
foreach (var product in products)
{
int orderedQty = 0;
List<BillEntry> billEntries = new List<BillEntry>();
foreach(var validateWeekBasket in _context.ValidatedWeekBaskets.Include(x => x.Products))
{
validateWeekBasket.Products.Where(x => x.ProductId == product.Id).ToList().ForEach(x=> orderedQty +=x.Quantity);
}
vmProducts.Add(new ProductViewModel(product, orderedQty));
}
return JsonConvert.SerializeObject(vmProducts, Formatting.Indented, new JsonSerializerSettings() {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
}
// GET: ProductsManagement/Details/5
[Authorize(Roles = Configurations.UserType_Producer)]
public IActionResult Details(Guid? id)
{
if (id == null)
{
return HttpNotFound();
}
Product product = _context.Products.Single(m => m.Id == id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// GET: ProductsManagement/Create
[Authorize(Roles = Configurations.UserType_Producer)]
public IActionResult Manage(Guid? id)
{
Product product = id == null ? new Product() : _context.Products.Include(x=>x.Familly).First(x => x.Id == id);
return View(new ProductEditionViewModel(product, _context,id == null));
}
// POST: ProductsManagement/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = Configurations.UserType_Producer)]
public async Task<IActionResult> Manage(ProductEditionViewModel vmProduct)
{
if (ModelState.IsValid)
{
//Set Labels
vmProduct.Product.SetLabels(vmProduct.SelectedLabels);
//Set Product familly (si ça retourne null c'est que la famille selectionnée n'existe pas, alors on est dans la merde)
vmProduct.Product.Familly = _context.ProductFamillys.FirstOrDefault(x => x.FamillyName == vmProduct.FamillyName);
//Set Producer (si ça retourne null, c'est que c'est pas un producteur qui est logger, alors on est dans la merde)
var appUser = await GetCurrentUserAsync();
vmProduct.Product.Producer = _context.Producers.FirstOrDefault(x => x.Email == appUser.Email);
//On s'occupe des images du produit
int cpt = 0;
foreach (IFormFile uploadFile in new List<IFormFile>() { vmProduct.UploadFile1, vmProduct.UploadFile2, vmProduct.UploadFile3 })
{
if (uploadFile != null)
{
//Image uploading
string fileName = await Configurations.UploadAndResizeImageFile(_environment, uploadFile, Configurations.ProductsStockagePath);
if(!vmProduct.IsNew && vmProduct.Product.Pictures.Count > cpt)
{
//Replace
vmProduct.Product.Pictures[cpt] = fileName;
}
else
{
//Add
vmProduct.Product.Pictures.Add(fileName);
}
}
cpt++;
}
if(vmProduct.IsNew)
{
vmProduct.Product.Id = Guid.NewGuid();
_context.Products.Add(vmProduct.Product);
}
else
{
_context.Products.Update(vmProduct.Product);
}
_context.SaveChanges();
return RedirectToAction("Index");
}
vmProduct.RefreshTypes(_context);
return View(vmProduct);
}
// GET: ProductsManagement/Delete/5
[ActionName("Delete")]
[Authorize(Roles = Configurations.UserType_Producer)]
public IActionResult Delete(Guid? id)
{
if (id == null)
{
return HttpNotFound();
}
Product product = _context.Products.Single(m => m.Id == id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// POST: ProductsManagement/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize(Roles = Configurations.UserType_Producer)]
public IActionResult DeleteConfirmed(Guid id)
{
Product product = _context.Products.Single(m => m.Id == id);
_context.Products.Remove(product);
_context.SaveChanges();
return RedirectToAction("Index");
}
[Authorize(Roles = Configurations.UserType_Producer)]
public IActionResult Enable(Guid? id)
{
_context.Products.First(x => x.Id == id).State = Product.ProductState.Enabled;
_context.SaveChanges();
return RedirectToAction("Index");
}
[Authorize(Roles = Configurations.UserType_Producer)]
public IActionResult EnableAllStockProduct()
{
foreach(var product in _context.Products.Where(x => x.State == Product.ProductState.Stock))
{
product.State = Product.ProductState.Enabled;
}
_context.SaveChanges();
return RedirectToAction("Index");
}
[Authorize(Roles = Configurations.UserType_Producer)]
public IActionResult DisableAllProduct()
{
foreach (var product in _context.Products.Where(x => x.State != Product.ProductState.Disabled))
{
product.State = Product.ProductState.Disabled;
}
_context.SaveChanges();
return RedirectToAction("Index");
}
[Authorize(Roles = Configurations.UserType_Producer)]
public IActionResult Disable(Guid? id)
{
_context.Products.First(x => x.Id == id).State = Product.ProductState.Disabled;
_context.SaveChanges();
return RedirectToAction("Index");
}
[Authorize(Roles = Configurations.UserType_Producer)]
[HttpPost, ActionName("ChangeStock")]
public IActionResult ChangeStock(Guid id, float newStock)
{
_context.Products.First(x => x.Id == id).WeekStock = newStock;
_context.Products.First(x => x.Id == id).RemainingStock = newStock;
_context.SaveChanges();
return Ok();
}
[Authorize(Roles = Configurations.UserType_Producer)]
[HttpPost, ActionName("ChangeCurrentStock")]
public IActionResult ChangeCurrentStock(Guid id, float newStock)
{
_context.Products.First(x => x.Id == id).RemainingStock = newStock;
_context.SaveChanges();
return Ok();
}
[Authorize(Roles = Configurations.UserType_Producer)]
private ApplicationUser GetCurrentUserSync()
{
return _userManager.FindByIdAsync(HttpContext.User.GetUserId()).GetAwaiter().GetResult();
}
[Authorize(Roles = Configurations.UserType_Producer)]
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ControlLibrary
{
public partial class SerializationComponent : Component
{
public SerializationComponent()
{
InitializeComponent();
}
public SerializationComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void SaveData<T>(List<T> data, string path)
{
foreach (var temp in data)
{
var typeTemp = temp.GetType().CustomAttributes;
if (typeTemp.Count() == 0)
{
MessageBox.Show("Не указаны аттрибуты");
return;
}
foreach (var t in typeTemp)
{
if (!(t.AttributeType.Name.Equals("DataContractAttribute")))
{
MessageBox.Show("Объект не поддерживает json сериализацию!");
return;
}
}
}
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(List<T>));
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
jsonSerializer.WriteObject(fs, data);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class failCanyon : MonoBehaviour
{
[SerializeField] GameObject failer;
// Start is called before the first frame update
void OnTriggerEnter(Collider other)
{
failer.SetActive(true);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Terminal.Gui;
using Xunit;
using Xunit.Abstractions;
// Alias Console to MockConsole so we don't accidentally use Console
using Console = Terminal.Gui.FakeConsole;
namespace Terminal.Gui.TypeTests {
public class DimTests {
readonly ITestOutputHelper output;
public DimTests (ITestOutputHelper output)
{
this.output = output;
Console.OutputEncoding = System.Text.Encoding.Default;
// Change current culture
var culture = CultureInfo.CreateSpecificCulture ("en-US");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
[Fact]
public void New_Works ()
{
var dim = new Dim ();
Assert.Equal ("Terminal.Gui.Dim", dim.ToString ());
}
[Fact]
public void Sized_SetsValue ()
{
var dim = Dim.Sized (0);
Assert.Equal ("Dim.Absolute(0)", dim.ToString ());
int testVal = 5;
dim = Dim.Sized (testVal);
Assert.Equal ($"Dim.Absolute({testVal})", dim.ToString ());
testVal = -1;
dim = Dim.Sized (testVal);
Assert.Equal ($"Dim.Absolute({testVal})", dim.ToString ());
}
[Fact]
public void Sized_Equals ()
{
int n1 = 0;
int n2 = 0;
var dim1 = Dim.Sized (n1);
var dim2 = Dim.Sized (n2);
Assert.Equal (dim1, dim2);
n1 = n2 = 1;
dim1 = Dim.Sized (n1);
dim2 = Dim.Sized (n2);
Assert.Equal (dim1, dim2);
n1 = n2 = -1;
dim1 = Dim.Sized (n1);
dim2 = Dim.Sized (n2);
Assert.Equal (dim1, dim2);
n1 = 0;
n2 = 1;
dim1 = Dim.Sized (n1);
dim2 = Dim.Sized (n2);
Assert.NotEqual (dim1, dim2);
}
[Fact]
public void Width_SetsValue ()
{
var dim = Dim.Width (null);
Assert.Throws<NullReferenceException> (() => dim.ToString ());
var testVal = Rect.Empty;
testVal = Rect.Empty;
dim = Dim.Width (new View (testVal));
Assert.Equal ($"DimView(side=Width, target=View()({{X={testVal.X},Y={testVal.Y},Width={testVal.Width},Height={testVal.Height}}}))", dim.ToString ());
testVal = new Rect (1, 2, 3, 4);
dim = Dim.Width (new View (testVal));
Assert.Equal ($"DimView(side=Width, target=View()({{X={testVal.X},Y={testVal.Y},Width={testVal.Width},Height={testVal.Height}}}))", dim.ToString ());
}
[Fact]
public void Width_Equals ()
{
var testRect1 = Rect.Empty;
var view1 = new View (testRect1);
var testRect2 = Rect.Empty;
var view2 = new View (testRect2);
var dim1 = Dim.Width (view1);
var dim2 = Dim.Width (view1);
// FIXED: Dim.Width should support Equals() and this should change to Equal.
Assert.Equal (dim1, dim2);
dim2 = Dim.Width (view2);
Assert.NotEqual (dim1, dim2);
testRect1 = new Rect (0, 1, 2, 3);
view1 = new View (testRect1);
testRect2 = new Rect (0, 1, 2, 3);
dim1 = Dim.Width (view1);
dim2 = Dim.Width (view1);
// FIXED: Dim.Width should support Equals() and this should change to Equal.
Assert.Equal (dim1, dim2);
Assert.Throws<ArgumentException> (() => new Rect (0, -1, -2, -3));
testRect1 = new Rect (0, -1, 2, 3);
view1 = new View (testRect1);
testRect2 = new Rect (0, -1, 2, 3);
dim1 = Dim.Width (view1);
dim2 = Dim.Width (view1);
// FIXED: Dim.Width should support Equals() and this should change to Equal.
Assert.Equal (dim1, dim2);
testRect1 = new Rect (0, -1, 2, 3);
view1 = new View (testRect1);
testRect2 = Rect.Empty;
view2 = new View (testRect2);
dim1 = Dim.Width (view1);
dim2 = Dim.Width (view2);
Assert.NotEqual (dim1, dim2);
}
[Fact]
public void Height_SetsValue ()
{
var dim = Dim.Height (null);
Assert.Throws<NullReferenceException> (() => dim.ToString ());
var testVal = Rect.Empty;
testVal = Rect.Empty;
dim = Dim.Height (new View (testVal));
Assert.Equal ($"DimView(side=Height, target=View()({{X={testVal.X},Y={testVal.Y},Width={testVal.Width},Height={testVal.Height}}}))", dim.ToString ());
testVal = new Rect (1, 2, 3, 4);
dim = Dim.Height (new View (testVal));
Assert.Equal ($"DimView(side=Height, target=View()({{X={testVal.X},Y={testVal.Y},Width={testVal.Width},Height={testVal.Height}}}))", dim.ToString ());
}
// TODO: Other Dim.Height tests (e.g. Equal?)
[Fact]
public void Fill_SetsValue ()
{
var testMargin = 0;
var dim = Dim.Fill ();
Assert.Equal ($"Dim.Fill(margin={testMargin})", dim.ToString ());
testMargin = 0;
dim = Dim.Fill (testMargin);
Assert.Equal ($"Dim.Fill(margin={testMargin})", dim.ToString ());
testMargin = 5;
dim = Dim.Fill (testMargin);
Assert.Equal ($"Dim.Fill(margin={testMargin})", dim.ToString ());
}
[Fact]
public void Fill_Equal ()
{
var margin1 = 0;
var margin2 = 0;
var dim1 = Dim.Fill (margin1);
var dim2 = Dim.Fill (margin2);
Assert.Equal (dim1, dim2);
}
[Fact]
public void Percent_SetsValue ()
{
float f = 0;
var dim = Dim.Percent (f);
Assert.Equal ($"Dim.Factor(factor={f / 100:0.###}, remaining={false})", dim.ToString ());
f = 0.5F;
dim = Dim.Percent (f);
Assert.Equal ($"Dim.Factor(factor={f / 100:0.###}, remaining={false})", dim.ToString ());
f = 100;
dim = Dim.Percent (f);
Assert.Equal ($"Dim.Factor(factor={f / 100:0.###}, remaining={false})", dim.ToString ());
}
[Fact]
public void Percent_Equals ()
{
float n1 = 0;
float n2 = 0;
var dim1 = Dim.Percent (n1);
var dim2 = Dim.Percent (n2);
Assert.Equal (dim1, dim2);
n1 = n2 = 1;
dim1 = Dim.Percent (n1);
dim2 = Dim.Percent (n2);
Assert.Equal (dim1, dim2);
n1 = n2 = 0.5f;
dim1 = Dim.Percent (n1);
dim2 = Dim.Percent (n2);
Assert.Equal (dim1, dim2);
n1 = n2 = 100f;
dim1 = Dim.Percent (n1);
dim2 = Dim.Percent (n2);
Assert.Equal (dim1, dim2);
n1 = n2 = 0.3f;
dim1 = Dim.Percent (n1, true);
dim2 = Dim.Percent (n2, true);
Assert.Equal (dim1, dim2);
n1 = n2 = 0.3f;
dim1 = Dim.Percent (n1);
dim2 = Dim.Percent (n2, true);
Assert.NotEqual (dim1, dim2);
n1 = 0;
n2 = 1;
dim1 = Dim.Percent (n1);
dim2 = Dim.Percent (n2);
Assert.NotEqual (dim1, dim2);
n1 = 0.5f;
n2 = 1.5f;
dim1 = Dim.Percent (n1);
dim2 = Dim.Percent (n2);
Assert.NotEqual (dim1, dim2);
}
[Fact]
public void Percent_ThrowsOnIvalid ()
{
var dim = Dim.Percent (0);
Assert.Throws<ArgumentException> (() => dim = Dim.Percent (-1));
Assert.Throws<ArgumentException> (() => dim = Dim.Percent (101));
Assert.Throws<ArgumentException> (() => dim = Dim.Percent (100.0001F));
Assert.Throws<ArgumentException> (() => dim = Dim.Percent (1000001));
}
[Fact]
public void ForceValidatePosDim_True_Dim_Validation_Throws_If_NewValue_Is_DimAbsolute_And_OldValue_Is_Another_Type ()
{
Application.Init (new FakeDriver ());
var t = Application.Top;
var w = new Window ("w") {
Width = Dim.Fill (0),
Height = Dim.Sized (10)
};
var v = new View ("v") {
Width = Dim.Width (w) - 2,
Height = Dim.Percent (10),
ForceValidatePosDim = true
};
w.Add (v);
t.Add (w);
t.Ready += () => {
Assert.Equal (2, w.Width = 2);
Assert.Equal (2, w.Height = 2);
Assert.Throws<ArgumentException> (() => v.Width = 2);
Assert.Throws<ArgumentException> (() => v.Height = 2);
v.ForceValidatePosDim = false;
var exception = Record.Exception (() => v.Width = 2);
Assert.Null (exception);
Assert.Equal (2, v.Width);
exception = Record.Exception (() => v.Height = 2);
Assert.Null (exception);
Assert.Equal (2, v.Height);
};
Application.Iteration += () => Application.RequestStop ();
Application.Run ();
Application.Shutdown ();
}
[Fact]
public void Dim_Validation_Do_Not_Throws_If_NewValue_Is_DimAbsolute_And_OldValue_Is_Null ()
{
Application.Init (new FakeDriver ());
var t = Application.Top;
var w = new Window (new Rect (1, 2, 4, 5), "w");
t.Add (w);
t.Ready += () => {
Assert.Equal (3, w.Width = 3);
Assert.Equal (4, w.Height = 4);
};
Application.Iteration += () => Application.RequestStop ();
Application.Run ();
Application.Shutdown ();
}
[Fact]
public void Dim_Validation_Do_Not_Throws_If_NewValue_Is_DimAbsolute_And_OldValue_Is_Another_Type_After_Sets_To_LayoutStyle_Absolute ()
{
Application.Init (new FakeDriver ());
var t = Application.Top;
var w = new Window ("w") {
Width = Dim.Fill (0),
Height = Dim.Sized (10)
};
var v = new View ("v") {
Width = Dim.Width (w) - 2,
Height = Dim.Percent (10)
};
w.Add (v);
t.Add (w);
t.Ready += () => {
v.LayoutStyle = LayoutStyle.Absolute;
Assert.Equal (2, v.Width = 2);
Assert.Equal (2, v.Height = 2);
};
Application.Iteration += () => Application.RequestStop ();
Application.Run ();
Application.Shutdown ();
}
[Fact]
public void Only_DimAbsolute_And_DimFactor_As_A_Different_Procedure_For_Assigning_Value_To_Width_Or_Height ()
{
// Testing with the Button because it properly handles the Dim class.
Application.Init (new FakeDriver ());
var t = Application.Top;
var w = new Window ("w") {
Width = 100,
Height = 100
};
var f1 = new FrameView ("f1") {
X = 0,
Y = 0,
Width = Dim.Percent (50),
Height = 5
};
var f2 = new FrameView ("f2") {
X = Pos.Right (f1),
Y = 0,
Width = Dim.Fill (),
Height = 5
};
var v1 = new Button ("v1") {
AutoSize = false,
X = Pos.X (f1) + 2,
Y = Pos.Bottom (f1) + 2,
Width = Dim.Width (f1) - 2,
Height = Dim.Fill () - 2,
ForceValidatePosDim = true
};
var v2 = new Button ("v2") {
AutoSize = false,
X = Pos.X (f2) + 2,
Y = Pos.Bottom (f2) + 2,
Width = Dim.Width (f2) - 2,
Height = Dim.Fill () - 2,
ForceValidatePosDim = true
};
var v3 = new Button ("v3") {
AutoSize = false,
Width = Dim.Percent (10),
Height = Dim.Percent (10),
ForceValidatePosDim = true
};
var v4 = new Button ("v4") {
AutoSize = false,
Width = Dim.Sized (50),
Height = Dim.Sized (50),
ForceValidatePosDim = true
};
var v5 = new Button ("v5") {
AutoSize = false,
Width = Dim.Width (v1) - Dim.Width (v3),
Height = Dim.Height (v1) - Dim.Height (v3),
ForceValidatePosDim = true
};
var v6 = new Button ("v6") {
AutoSize = false,
X = Pos.X (f2),
Y = Pos.Bottom (f2) + 2,
Width = Dim.Percent (20, true),
Height = Dim.Percent (20, true),
ForceValidatePosDim = true
};
w.Add (f1, f2, v1, v2, v3, v4, v5, v6);
t.Add (w);
t.Ready += () => {
Assert.Equal ("Dim.Absolute(100)", w.Width.ToString ());
Assert.Equal ("Dim.Absolute(100)", w.Height.ToString ());
Assert.Equal (100, w.Frame.Width);
Assert.Equal (100, w.Frame.Height);
Assert.Equal ("Dim.Factor(factor=0.5, remaining=False)", f1.Width.ToString ());
Assert.Equal ("Dim.Absolute(5)", f1.Height.ToString ());
Assert.Equal (49, f1.Frame.Width); // 50-1=49
Assert.Equal (5, f1.Frame.Height);
Assert.Equal ("Dim.Fill(margin=0)", f2.Width.ToString ());
Assert.Equal ("Dim.Absolute(5)", f2.Height.ToString ());
Assert.Equal (49, f2.Frame.Width); // 50-1=49
Assert.Equal (5, f2.Frame.Height);
Assert.Equal ("Dim.Combine(DimView(side=Width, target=FrameView()({X=0,Y=0,Width=49,Height=5}))-Dim.Absolute(2))", v1.Width.ToString ());
Assert.Equal ("Dim.Combine(Dim.Fill(margin=0)-Dim.Absolute(2))", v1.Height.ToString ());
Assert.Equal (47, v1.Frame.Width); // 49-2=47
Assert.Equal (89, v1.Frame.Height); // 98-5-2-2=89
Assert.Equal ("Dim.Combine(DimView(side=Width, target=FrameView()({X=49,Y=0,Width=49,Height=5}))-Dim.Absolute(2))", v2.Width.ToString ());
Assert.Equal ("Dim.Combine(Dim.Fill(margin=0)-Dim.Absolute(2))", v2.Height.ToString ());
Assert.Equal (47, v2.Frame.Width); // 49-2=47
Assert.Equal (89, v2.Frame.Height); // 98-5-2-2=89
Assert.Equal ("Dim.Factor(factor=0.1, remaining=False)", v3.Width.ToString ());
Assert.Equal ("Dim.Factor(factor=0.1, remaining=False)", v3.Height.ToString ());
Assert.Equal (9, v3.Frame.Width); // 98*10%=9
Assert.Equal (9, v3.Frame.Height); // 98*10%=9
Assert.Equal ("Dim.Absolute(50)", v4.Width.ToString ());
Assert.Equal ("Dim.Absolute(50)", v4.Height.ToString ());
Assert.Equal (50, v4.Frame.Width);
Assert.Equal (50, v4.Frame.Height);
Assert.Equal ("Dim.Combine(DimView(side=Width, target=Button()({X=2,Y=7,Width=47,Height=89}))-DimView(side=Width, target=Button()({X=0,Y=0,Width=9,Height=9})))", v5.Width.ToString ());
Assert.Equal ("Dim.Combine(DimView(side=Height, target=Button()({X=2,Y=7,Width=47,Height=89}))-DimView(side=Height, target=Button()({X=0,Y=0,Width=9,Height=9})))", v5.Height.ToString ());
Assert.Equal (38, v5.Frame.Width); // 47-9=38
Assert.Equal (80, v5.Frame.Height); // 89-9=80
Assert.Equal ("Dim.Factor(factor=0.2, remaining=True)", v6.Width.ToString ());
Assert.Equal ("Dim.Factor(factor=0.2, remaining=True)", v6.Height.ToString ());
Assert.Equal (9, v6.Frame.Width); // 47*20%=9
Assert.Equal (18, v6.Frame.Height); // 89*20%=18
w.Width = 200;
w.Height = 200;
t.LayoutSubviews ();
Assert.Equal ("Dim.Absolute(200)", w.Width.ToString ());
Assert.Equal ("Dim.Absolute(200)", w.Height.ToString ());
Assert.Equal (200, w.Frame.Width);
Assert.Equal (200, w.Frame.Height);
f1.Text = "Frame1";
Assert.Equal ("Dim.Factor(factor=0.5, remaining=False)", f1.Width.ToString ());
Assert.Equal ("Dim.Absolute(5)", f1.Height.ToString ());
Assert.Equal (99, f1.Frame.Width); // 100-1=99
Assert.Equal (5, f1.Frame.Height);
f2.Text = "Frame2";
Assert.Equal ("Dim.Fill(margin=0)", f2.Width.ToString ());
Assert.Equal ("Dim.Absolute(5)", f2.Height.ToString ());
Assert.Equal (99, f2.Frame.Width); // 100-1=99
Assert.Equal (5, f2.Frame.Height);
v1.Text = "Button1";
Assert.Equal ("Dim.Combine(DimView(side=Width, target=FrameView()({X=0,Y=0,Width=99,Height=5}))-Dim.Absolute(2))", v1.Width.ToString ());
Assert.Equal ("Dim.Combine(Dim.Fill(margin=0)-Dim.Absolute(2))", v1.Height.ToString ());
Assert.Equal (97, v1.Frame.Width); // 99-2=97
Assert.Equal (189, v1.Frame.Height); // 198-2-7=189
v2.Text = "Button2";
Assert.Equal ("Dim.Combine(DimView(side=Width, target=FrameView()({X=99,Y=0,Width=99,Height=5}))-Dim.Absolute(2))", v2.Width.ToString ());
Assert.Equal ("Dim.Combine(Dim.Fill(margin=0)-Dim.Absolute(2))", v2.Height.ToString ());
Assert.Equal (97, v2.Frame.Width); // 99-2=97
Assert.Equal (189, v2.Frame.Height); // 198-2-7=189
v3.Text = "Button3";
Assert.Equal ("Dim.Factor(factor=0.1, remaining=False)", v3.Width.ToString ());
Assert.Equal ("Dim.Factor(factor=0.1, remaining=False)", v3.Height.ToString ());
Assert.Equal (19, v3.Frame.Width); // 198*10%=19 * Percent is related to the super-view if it isn't null otherwise the view width
Assert.Equal (19, v3.Frame.Height); // 199*10%=19
v4.Text = "Button4";
v4.AutoSize = false;
Assert.Equal ("Dim.Absolute(50)", v4.Width.ToString ());
Assert.Equal ("Dim.Absolute(50)", v4.Height.ToString ());
Assert.Equal (50, v4.Frame.Width);
Assert.Equal (50, v4.Frame.Height);
v4.AutoSize = true;
Assert.Equal ("Dim.Absolute(11)", v4.Width.ToString ());
Assert.Equal ("Dim.Absolute(1)", v4.Height.ToString ());
Assert.Equal (11, v4.Frame.Width); // 11 is the text length and because is Dim.DimAbsolute
Assert.Equal (1, v4.Frame.Height); // 1 because is Dim.DimAbsolute
v5.Text = "Button5";
Assert.Equal ("Dim.Combine(DimView(side=Width, target=Button()({X=2,Y=7,Width=97,Height=189}))-DimView(side=Width, target=Button()({X=0,Y=0,Width=19,Height=19})))", v5.Width.ToString ());
Assert.Equal ("Dim.Combine(DimView(side=Height, target=Button()({X=2,Y=7,Width=97,Height=189}))-DimView(side=Height, target=Button()({X=0,Y=0,Width=19,Height=19})))", v5.Height.ToString ());
Assert.Equal (78, v5.Frame.Width); // 97-19=78
Assert.Equal (170, v5.Frame.Height); // 189-19=170
v6.Text = "Button6";
Assert.Equal ("Dim.Factor(factor=0.2, remaining=True)", v6.Width.ToString ());
Assert.Equal ("Dim.Factor(factor=0.2, remaining=True)", v6.Height.ToString ());
Assert.Equal (19, v6.Frame.Width); // 99*20%=19
Assert.Equal (38, v6.Frame.Height); // 198-7*20=38
};
Application.Iteration += () => Application.RequestStop ();
Application.Run ();
Application.Shutdown ();
}
// DONE: Test operators
[Fact]
public void DimCombine_Do_Not_Throws ()
{
Application.Init (new FakeDriver ());
var t = Application.Top;
var w = new Window ("w") {
Width = Dim.Width (t) - 2,
Height = Dim.Height (t) - 2
};
var f = new FrameView ("f");
var v1 = new View ("v1") {
Width = Dim.Width (w) - 2,
Height = Dim.Height (w) - 2
};
var v2 = new View ("v2") {
Width = Dim.Width (v1) - 2,
Height = Dim.Height (v1) - 2
};
f.Add (v1, v2);
w.Add (f);
t.Add (w);
f.Width = Dim.Width (t) - Dim.Width (v2);
f.Height = Dim.Height (t) - Dim.Height (v2);
t.Ready += () => {
Assert.Equal (80, t.Frame.Width);
Assert.Equal (25, t.Frame.Height);
Assert.Equal (78, w.Frame.Width);
Assert.Equal (23, w.Frame.Height);
Assert.Equal (6, f.Frame.Width);
Assert.Equal (6, f.Frame.Height);
Assert.Equal (76, v1.Frame.Width);
Assert.Equal (21, v1.Frame.Height);
Assert.Equal (74, v2.Frame.Width);
Assert.Equal (19, v2.Frame.Height);
};
Application.Iteration += () => Application.RequestStop ();
Application.Run ();
Application.Shutdown ();
}
[Fact]
public void PosCombine_Will_Throws ()
{
Application.Init (new FakeDriver ());
var t = Application.Top;
var w = new Window ("w") {
Width = Dim.Width (t) - 2,
Height = Dim.Height (t) - 2
};
var f = new FrameView ("f");
var v1 = new View ("v1") {
Width = Dim.Width (w) - 2,
Height = Dim.Height (w) - 2
};
var v2 = new View ("v2") {
Width = Dim.Width (v1) - 2,
Height = Dim.Height (v1) - 2
};
f.Add (v1); // v2 not added
w.Add (f);
t.Add (w);
f.Width = Dim.Width (t) - Dim.Width (v2);
f.Height = Dim.Height (t) - Dim.Height (v2);
Assert.Throws<InvalidOperationException> (() => Application.Run ());
Application.Shutdown ();
}
[Fact]
public void Dim_Add_Operator ()
{
Application.Init (new FakeDriver ());
var top = Application.Top;
var view = new View () { X = 0, Y = 0, Width = 20, Height = 0 };
var field = new TextField () { X = 0, Y = Pos.Bottom (view), Width = 20 };
var count = 0;
field.KeyDown += (k) => {
if (k.KeyEvent.Key == Key.Enter) {
field.Text = $"Label {count}";
var label = new Label (field.Text) { X = 0, Y = view.Bounds.Height, Width = 20 };
view.Add (label);
Assert.Equal ($"Label {count}", label.Text);
Assert.Equal ($"Pos.Absolute({count})", label.Y.ToString ());
Assert.Equal ($"Dim.Absolute({count})", view.Height.ToString ());
view.Height += 1;
count++;
Assert.Equal ($"Dim.Absolute({count})", view.Height.ToString ());
}
};
Application.Iteration += () => {
while (count < 20) field.OnKeyDown (new KeyEvent (Key.Enter, new KeyModifiers ()));
Application.RequestStop ();
};
var win = new Window ();
win.Add (view);
win.Add (field);
top.Add (win);
Application.Run (top);
Assert.Equal (20, count);
// Shutdown must be called to safely clean up Application if Init has been called
Application.Shutdown ();
}
private string [] expecteds = new string [21] {
@"
┌────────────────────┐
│View with long text │
│ │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 0 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 1 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 2 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 3 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 4 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 5 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 6 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 7 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 8 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 9 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 10 │
│Label 10 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 10 │
│Label 11 │
│Label 11 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 10 │
│Label 11 │
│Label 12 │
│Label 12 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 10 │
│Label 11 │
│Label 12 │
│Label 13 │
│Label 13 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 10 │
│Label 11 │
│Label 12 │
│Label 13 │
│Label 14 │
│Label 14 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 10 │
│Label 11 │
│Label 12 │
│Label 13 │
│Label 14 │
│Label 15 │
│Label 15 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 10 │
│Label 11 │
│Label 12 │
│Label 13 │
│Label 14 │
│Label 15 │
│Label 16 │
│Label 16 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 10 │
│Label 11 │
│Label 12 │
│Label 13 │
│Label 14 │
│Label 15 │
│Label 16 │
│Label 17 │
│Label 17 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 10 │
│Label 11 │
│Label 12 │
│Label 13 │
│Label 14 │
│Label 15 │
│Label 16 │
│Label 17 │
│Label 18 │
│Label 18 │
└────────────────────┘",
@"
┌────────────────────┐
│View with long text │
│Label 0 │
│Label 1 │
│Label 2 │
│Label 3 │
│Label 4 │
│Label 5 │
│Label 6 │
│Label 7 │
│Label 8 │
│Label 9 │
│Label 10 │
│Label 11 │
│Label 12 │
│Label 13 │
│Label 14 │
│Label 15 │
│Label 16 │
│Label 17 │
│Label 18 │
│Label 19 │
│Label 19 │
└────────────────────┘",
};
[Fact]
public void Dim_Add_Operator_With_Text ()
{
Application.Init (new FakeDriver ());
var top = Application.Top;
// Although view height is zero the text it's draw due the SetMinWidthHeight method
var view = new View ("View with long text") { X = 0, Y = 0, Width = 20, Height = 0 };
var field = new TextField () { X = 0, Y = Pos.Bottom (view), Width = 20 };
var count = 0;
var listLabels = new List<Label> ();
field.KeyDown += (k) => {
if (k.KeyEvent.Key == Key.Enter) {
((FakeDriver)Application.Driver).SetBufferSize (22, count + 4);
var pos = TestHelpers.AssertDriverContentsWithFrameAre (expecteds [count], output);
Assert.Equal (new Rect (0, 0, 22, count + 4), pos);
if (count < 20) {
field.Text = $"Label {count}";
var label = new Label (field.Text) { X = 0, Y = view.Bounds.Height, Width = 10 };
view.Add (label);
Assert.Equal ($"Label {count}", label.Text);
Assert.Equal ($"Pos.Absolute({count + 1})", label.Y.ToString ());
listLabels.Add (label);
if (count == 0) {
Assert.Equal ($"Dim.Absolute({count})", view.Height.ToString ());
view.Height += 2;
} else {
Assert.Equal ($"Dim.Absolute({count + 1})", view.Height.ToString ());
view.Height += 1;
}
count++;
}
Assert.Equal ($"Dim.Absolute({count + 1})", view.Height.ToString ());
}
};
Application.Iteration += () => {
while (count < 21) {
field.OnKeyDown (new KeyEvent (Key.Enter, new KeyModifiers ()));
if (count == 20) {
field.OnKeyDown (new KeyEvent (Key.Enter, new KeyModifiers ()));
break;
}
}
Application.RequestStop ();
};
var win = new Window ();
win.Add (view);
win.Add (field);
top.Add (win);
Application.Run (top);
Assert.Equal (20, count);
Assert.Equal (count, listLabels.Count);
// Shutdown must be called to safely clean up Application if Init has been called
Application.Shutdown ();
}
[Fact]
public void Dim_Subtract_Operator ()
{
Application.Init (new FakeDriver ());
var top = Application.Top;
var view = new View () { X = 0, Y = 0, Width = 20, Height = 0 };
var field = new TextField () { X = 0, Y = Pos.Bottom (view), Width = 20 };
var count = 20;
var listLabels = new List<Label> ();
for (int i = 0; i < count; i++) {
field.Text = $"Label {i}";
var label = new Label (field.Text) { X = 0, Y = view.Bounds.Height, Width = 20 };
view.Add (label);
Assert.Equal ($"Label {i}", label.Text);
Assert.Equal ($"Pos.Absolute({i})", label.Y.ToString ());
listLabels.Add (label);
Assert.Equal ($"Dim.Absolute({i})", view.Height.ToString ());
view.Height += 1;
Assert.Equal ($"Dim.Absolute({i + 1})", view.Height.ToString ());
}
field.KeyDown += (k) => {
if (k.KeyEvent.Key == Key.Enter) {
Assert.Equal ($"Label {count - 1}", listLabels [count - 1].Text);
view.Remove (listLabels [count - 1]);
Assert.Equal ($"Dim.Absolute({count})", view.Height.ToString ());
view.Height -= 1;
count--;
Assert.Equal ($"Dim.Absolute({count})", view.Height.ToString ());
}
};
Application.Iteration += () => {
while (count > 0) field.OnKeyDown (new KeyEvent (Key.Enter, new KeyModifiers ()));
Application.RequestStop ();
};
var win = new Window ();
win.Add (view);
win.Add (field);
top.Add (win);
Application.Run (top);
Assert.Equal (0, count);
// Shutdown must be called to safely clean up Application if Init has been called
Application.Shutdown ();
}
[Fact]
public void Dim_Subtract_Operator_With_Text ()
{
Application.Init (new FakeDriver ());
var top = Application.Top;
// Although view height is zero the text it's draw due the SetMinWidthHeight method
var view = new View ("View with long text") { X = 0, Y = 0, Width = 20, Height = 0 };
var field = new TextField () { X = 0, Y = Pos.Bottom (view), Width = 20 };
var count = 20;
var listLabels = new List<Label> ();
for (int i = 0; i < count; i++) {
field.Text = $"Label {i}";
var label = new Label (field.Text) { X = 0, Y = view.Bounds.Height, Width = 10 };
view.Add (label);
Assert.Equal ($"Label {i}", label.Text);
Assert.Equal ($"Pos.Absolute({i + 1})", label.Y.ToString ());
listLabels.Add (label);
if (i == 0) {
Assert.Equal ($"Dim.Absolute({i})", view.Height.ToString ());
view.Height += 2;
Assert.Equal ($"Dim.Absolute({i + 2})", view.Height.ToString ());
} else {
Assert.Equal ($"Dim.Absolute({i + 1})", view.Height.ToString ());
view.Height += 1;
Assert.Equal ($"Dim.Absolute({i + 2})", view.Height.ToString ());
}
}
field.KeyDown += (k) => {
if (k.KeyEvent.Key == Key.Enter) {
((FakeDriver)Application.Driver).SetBufferSize (22, count + 4);
var pos = TestHelpers.AssertDriverContentsWithFrameAre (expecteds [count], output);
Assert.Equal (new Rect (0, 0, 22, count + 4), pos);
if (count > 0) {
Assert.Equal ($"Label {count - 1}", listLabels [count - 1].Text);
view.Remove (listLabels [count - 1]);
listLabels.RemoveAt (count - 1);
Assert.Equal ($"Dim.Absolute({count + 1})", view.Height.ToString ());
view.Height -= 1;
count--;
if (listLabels.Count > 0)
field.Text = listLabels [count - 1].Text;
else
field.Text = NStack.ustring.Empty;
}
Assert.Equal ($"Dim.Absolute({count + 1})", view.Height.ToString ());
}
};
Application.Iteration += () => {
while (count > -1) {
field.OnKeyDown (new KeyEvent (Key.Enter, new KeyModifiers ()));
if (count == 0) {
field.OnKeyDown (new KeyEvent (Key.Enter, new KeyModifiers ()));
break;
}
}
Application.RequestStop ();
};
var win = new Window ();
win.Add (view);
win.Add (field);
top.Add (win);
Application.Run (top);
Assert.Equal (0, count);
Assert.Equal (count, listLabels.Count);
// Shutdown must be called to safely clean up Application if Init has been called
Application.Shutdown ();
}
[Fact]
public void Internal_Tests ()
{
var dimFactor = new Dim.DimFactor (0.10F);
Assert.Equal (10, dimFactor.Anchor (100));
var dimAbsolute = new Dim.DimAbsolute (10);
Assert.Equal (10, dimAbsolute.Anchor (0));
var dimFill = new Dim.DimFill (1);
Assert.Equal (99, dimFill.Anchor (100));
var dimCombine = new Dim.DimCombine (true, dimFactor, dimAbsolute);
Assert.Equal (dimCombine.left, dimFactor);
Assert.Equal (dimCombine.right, dimAbsolute);
Assert.Equal (20, dimCombine.Anchor (100));
var view = new View (new Rect (20, 10, 20, 1));
var dimViewHeight = new Dim.DimView (view, 0);
Assert.Equal (1, dimViewHeight.Anchor (0));
var dimViewWidth = new Dim.DimView (view, 1);
Assert.Equal (20, dimViewWidth.Anchor (0));
}
[Fact]
public void Function_SetsValue ()
{
var text = "Test";
var dim = Dim.Function (() => text.Length);
Assert.Equal ("Dim.DimFunc(4)", dim.ToString ());
text = "New Test";
Assert.Equal ("Dim.DimFunc(8)", dim.ToString ());
text = "";
Assert.Equal ("Dim.DimFunc(0)", dim.ToString ());
}
[Fact]
public void Function_Equal ()
{
var f1 = () => 0;
var f2 = () => 0;
var dim1 = Dim.Function (f1);
var dim2 = Dim.Function (f2);
Assert.Equal (dim1, dim2);
f2 = () => 1;
dim2 = Dim.Function (f2);
Assert.NotEqual (dim1, dim2);
}
[Theory, AutoInitShutdown]
[InlineData (0, true)]
[InlineData (0, false)]
[InlineData (50, true)]
[InlineData (50, false)]
public void DimPercentPlusOne (int startingDistance, bool testHorizontal)
{
var container = new View {
Width = 100,
Height = 100,
};
var label = new Label {
X = testHorizontal ? startingDistance : 0,
Y = testHorizontal ? 0 : startingDistance,
Width = testHorizontal ? Dim.Percent (50) + 1 : 1,
Height = testHorizontal ? 1 : Dim.Percent (50) + 1,
};
container.Add (label);
Application.Top.Add (container);
Application.Top.LayoutSubviews ();
Assert.Equal (100, container.Frame.Width);
Assert.Equal (100, container.Frame.Height);
if (testHorizontal) {
Assert.Equal (51, label.Frame.Width);
Assert.Equal (1, label.Frame.Height);
} else {
Assert.Equal (1, label.Frame.Width);
Assert.Equal (51, label.Frame.Height);
}
}
}
}
|
using KartObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KartObjects.Entities;
namespace KartLib
{
[Serializable]
public class DiscountPromoAction : SimpleDbEntity
{
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
public override string FriendlyName
{
get { return "Скидка покупателя на кассе"; }
}
/// <summary>
/// Процент скидки
/// </summary>
public decimal DiscountPercent
{
get;
set;
}
/// <summary>
/// Условие суммы чека от
/// </summary>
public decimal? SumReceiptFrom
{
get;
set;
}
/// <summary>
/// Условие суммы чека по
/// </summary>
public decimal? SumReceiptTo
{
get;
set;
}
/// <summary>
/// Условие что была введена карта покупателя
/// </summary>
public bool CardEnteredCondition
{
get;
set;
}
/// <summary>
/// Значение для условия
/// </summary>
public decimal CondValue
{
get;
set;
}
/// <summary>
/// Условие что была введена карта покупателя
/// </summary>
public DiscountType discountType
{
get;
set;
}
/// <summary>
/// Идентификатор подразделения
/// </summary>
public long IdStore
{
get;
set;
}
/// <summary>
/// Время начала работы скидки
/// </summary>
public DateTime? TimeBegin
{
get;
set;
}
/// <summary>
/// Время конца работы скидки
/// </summary>
public DateTime? TimeEnd
{
get;
set;
}
public bool SatisfyCondition(ReceiptSpecRecord r)
{
if (discountType == DiscountType.GoodDiscount)
{
return r.IdAssortment == (long)CondValue;
}
else
return true;
}
}
}
|
using EduHome.DataContext;
using EduHome.Models.Entity;
using EduHome.ViewModels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EduHome.Areas.Admin.Controllers
{
[Area("admin")]
public class EventController : Controller
{
public EduhomeDbContext _context { get; }
public IWebHostEnvironment _env { get; }
public EventController(EduhomeDbContext context, IWebHostEnvironment env)
{
_context = context;
_env = env;
}
// GET: EventController
public IActionResult Index()
{
List<Event> @event = _context.Events.Include(e => e.Course).ThenInclude(c => c.Category).Include(e => e.TimeInterval).
Include(e => e.PostMessages).Include(e => e.EventSpeakers).ThenInclude(es => es.Speaker).ToList();
return View(@event);
}
// GET: EventController/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return NotFound();
}
Event @event = _context.Events.Include(e => e.Course).ThenInclude(c => c.Category).Include(e => e.TimeInterval).Include(e => e.PostMessages).
Include(e => e.EventSpeakers).ThenInclude(es => es.Speaker).Where(e => e.IsDeleted == false).FirstOrDefault(e => e.Id == id);
if (@event == null)
{
return BadRequest();
}
return View(@event);
}
// GET: EventController/Create
public IActionResult Create()
{
EventCategoryVM eventCategory = new EventCategoryVM
{
Courses = _context.Courses.Include(c => c.Category).Include(c => c.Feature).Include(c => c.Events).Include(c => c.Posts).ToList(),
TimeIntervals = _context.TimeIntervals.ToList()
};
return View(eventCategory);
}
// POST: EventController/Create
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(EventCategoryVM eventCategory)
{
if (!ModelState.IsValid)
{
return View(eventCategory.Event);
}
if (!eventCategory.Event.Photo.ContentType.Contains("image"))
{
return NotFound();
}
if (eventCategory.Event.Photo.Length / 1024 > 3000)
{
return NotFound();
}
string filename = Guid.NewGuid().ToString() + '-' + eventCategory.Event.Photo.FileName;
string environment = _env.WebRootPath;
string newSlider = Path.Combine(environment, "img", "event", filename);
using (FileStream file = new FileStream(newSlider, FileMode.Create))
{
eventCategory.Event.Photo.CopyTo(file);
}
eventCategory.Event.Image = filename;
_context.Events.Add(eventCategory.Event);
_context.SaveChanges();
return RedirectToAction(nameof(Index), eventCategory);
}
// GET: EventController/Edit/5
public IActionResult Update(int? id)
{
if (id == null)
{
return NotFound();
}
EventCategoryVM eventCategory = new EventCategoryVM
{
Event = _context.Events.Include(e => e.Course).ThenInclude(c => c.Category).Include(e => e.PostMessages).
Where(e => e.IsDeleted == false).FirstOrDefault(e => e.Id == id),
TimeIntervals = _context.TimeIntervals.ToList(),
Courses = _context.Courses.Include(c => c.Category).Include(c => c.Feature).Include(c => c.Events).
Include(c => c.Posts).ToList()
};
if (eventCategory.Event == null)
{
return BadRequest();
}
return View(eventCategory);
}
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Update(int? id, EventCategoryVM eventCategory)
{
if (id == null)
{
return NotFound();
}
//if user don't choose image program enter here
if (eventCategory.Event.Photo == null)
{
eventCategory.Event.Image = eventCategory.Image;
ModelState["Event.Photo"].ValidationState = ModelValidationState.Valid;
if (!ModelState.IsValid)
{
return View(eventCategory.Event);
}
_context.Events.Update(eventCategory.Event);
_context.SaveChanges();
return RedirectToAction(nameof(Index), eventCategory);
}
if (id != eventCategory.Event.Id)
{
return NotFound();
}
if (!eventCategory.Event.Photo.ContentType.Contains("image"))
{
return NotFound();
}
if (eventCategory.Event.Photo.Length / 1024 > 3000)
{
return NotFound();
}
//removing old image from local folder
string environment = _env.WebRootPath;
string folderPath = Path.Combine(environment, "img", "event", eventCategory.Image);
FileInfo oldFile = new FileInfo(folderPath);
if (System.IO.File.Exists(folderPath))
{
oldFile.Delete();
};
//coping new image in local folder
string filename = Guid.NewGuid().ToString() + '-' + eventCategory.Event.Photo.FileName;
string newSlider = Path.Combine(environment, "img", "event", filename);
using (FileStream newFile = new FileStream(newSlider, FileMode.Create))
{
eventCategory.Event.Photo.CopyTo(newFile);
}
eventCategory.Event.Image = filename;
if (!ModelState.IsValid)
{
return View(eventCategory.Event);
}
_context.Events.Update(eventCategory.Event);
_context.SaveChanges();
return RedirectToAction(nameof(Index), eventCategory);
}
// GET: EventController/Delete/5
public IActionResult DeleteOrActive(int? id)
{
if (id == null)
{
return NotFound();
}
Event @event = _context.Events.Include(e => e.Course).ThenInclude(c => c.Category).Include(e => e.TimeInterval).Include(e => e.EventSpeakers).
FirstOrDefault(e => e.Id == id);
if (@event == null)
{
return BadRequest();
}
if (@event.IsDeleted)
@event.IsDeleted = false;
else
@event.IsDeleted = true;
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
public IActionResult Comments()
{
List<PostMessage> postMessages = _context.PostMessages.Include(pm => pm.Contact).Include(pm => pm.Course).Include(pm => pm.Post).
Include(pm => pm.Event).Where(pm => pm.EventId != null).ToList();
return View(postMessages);
}
public IActionResult MakeDeleteOrActive(int? id)
{
if (id == null)
{
return NotFound();
}
PostMessage message = _context.PostMessages.Include(pm => pm.Contact).Include(pm => pm.Course).Include(pm => pm.Post).
Include(pm => pm.Event).Where(pm => pm.EventId != null).FirstOrDefault(pm => pm.Id == id);
if (message == null)
{
return BadRequest();
}
if (message.IsDeleted == true)
message.IsDeleted = false;
else
message.IsDeleted = true;
_context.PostMessages.Update(message);
_context.SaveChanges();
return RedirectToAction(nameof(Comments));
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class BoomerEnemy1 : Enemy1
{
public float stopDistance;
private float attackTime;
private Animator anim;
public Transform spitPoint;
public GameObject spit1;
//PhotonView view;
GameObject closestplayer = null;
public override void Start()
{
//view = GetComponent<PhotonView>();
base.Start();
anim = GetComponent<Animator>();
}
public override void Update()
{
base.Update();
// if (view.IsMine)
// {
if (players.Length > 0)
{
float disttoclosestplayer = Mathf.Infinity;
foreach (GameObject currentplayer in players)
{
float distanceToEnemy = (currentplayer.transform.position - this.transform.position).sqrMagnitude;
if (distanceToEnemy < disttoclosestplayer)
{
disttoclosestplayer = distanceToEnemy;
closestplayer = currentplayer;
}
}
if (Vector2.Distance(transform.position, closestplayer.transform.position) > stopDistance)
{
transform.position = Vector2.MoveTowards(transform.position, closestplayer.transform.position, speed * Time.deltaTime);
}
if (Time.time >= attackTime)
{
attackTime = Time.time + timeBetweenAttacks;
anim.SetTrigger("attack");
}
}
//}
}
public void RangedAttack()
{
if (view.IsMine)
{
if (players.Length > 0)
{
Vector2 direction = closestplayer.transform.position - spitPoint.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
spitPoint.rotation = rotation;
PhotonNetwork.Instantiate(spit1.name, spitPoint.position, spitPoint.rotation);
}
}
}
} |
using System;
using System.Windows.Forms;
using Project.Forms.Layouts;
using Project.Models;
using Project.Services;
using Project.Helpers;
using Project.Data;
namespace Project.Forms {
public partial class RoomCreate : BaseLayout {
private Panel panel;
private Label title;
private Label numberLabel;
private NumericUpDown numberInput;
private Label rowLabel;
private NumericUpDown rowInput;
private Label columnLabel;
private NumericUpDown columnInput;
private Label priceLabel;
private NumericUpDown priceInput;
private Button saveButton;
private Button cancelButton;
public RoomCreate() {
InitializeComponent();
}
public override string GetHandle() {
return "roomCreate";
}
public override bool RequireAdmin() {
return true;
}
public override void OnShow() {
base.OnShow();
// Clear inputs
numberInput.Text = "";
rowInput.Text = "";
columnInput.Text = "";
}
private void InitializeComponent() {
this.panel = new System.Windows.Forms.Panel();
this.columnInput = new System.Windows.Forms.NumericUpDown();
this.rowInput = new System.Windows.Forms.NumericUpDown();
this.numberInput = new System.Windows.Forms.NumericUpDown();
this.cancelButton = new System.Windows.Forms.Button();
this.saveButton = new System.Windows.Forms.Button();
this.title = new System.Windows.Forms.Label();
this.rowLabel = new System.Windows.Forms.Label();
this.columnLabel = new System.Windows.Forms.Label();
this.numberLabel = new System.Windows.Forms.Label();
this.priceLabel = new System.Windows.Forms.Label();
this.priceInput = new System.Windows.Forms.NumericUpDown();
this.panel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.columnInput)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.rowInput)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numberInput)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.priceInput)).BeginInit();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.priceInput);
this.panel.Controls.Add(this.priceLabel);
this.panel.Controls.Add(this.columnInput);
this.panel.Controls.Add(this.rowInput);
this.panel.Controls.Add(this.numberInput);
this.panel.Controls.Add(this.cancelButton);
this.panel.Controls.Add(this.saveButton);
this.panel.Controls.Add(this.title);
this.panel.Controls.Add(this.rowLabel);
this.panel.Controls.Add(this.columnLabel);
this.panel.Controls.Add(this.numberLabel);
this.panel.Location = new System.Drawing.Point(40, 115);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(993, 534);
this.panel.TabIndex = 20;
//
// columnInput
//
this.columnInput.Location = new System.Drawing.Point(125, 168);
this.columnInput.Name = "columnInput";
this.columnInput.Size = new System.Drawing.Size(495, 20);
this.columnInput.TabIndex = 26;
//
// rowInput
//
this.rowInput.Location = new System.Drawing.Point(125, 122);
this.rowInput.Name = "rowInput";
this.rowInput.Size = new System.Drawing.Size(495, 20);
this.rowInput.TabIndex = 25;
//
// numberInput
//
this.numberInput.Location = new System.Drawing.Point(125, 79);
this.numberInput.Name = "numberInput";
this.numberInput.Size = new System.Drawing.Size(495, 20);
this.numberInput.TabIndex = 24;
//
// cancelButton
//
this.cancelButton.Location = new System.Drawing.Point(276, 281);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(140, 23);
this.cancelButton.TabIndex = 23;
this.cancelButton.Text = "Annuleren";
this.cancelButton.UseVisualStyleBackColor = true;
this.cancelButton.Click += new System.EventHandler(this.CancelButton_Click);
//
// saveButton
//
this.saveButton.Location = new System.Drawing.Point(120, 281);
this.saveButton.Name = "saveButton";
this.saveButton.Size = new System.Drawing.Size(140, 23);
this.saveButton.TabIndex = 19;
this.saveButton.Text = "Opslaan";
this.saveButton.UseVisualStyleBackColor = true;
this.saveButton.Click += new System.EventHandler(this.SaveButton_Click);
//
// title
//
this.title.AutoSize = true;
this.title.Font = new System.Drawing.Font("Microsoft Sans Serif", 30F);
this.title.Location = new System.Drawing.Point(3, 0);
this.title.Name = "title";
this.title.Size = new System.Drawing.Size(293, 46);
this.title.TabIndex = 3;
this.title.Text = "Zaal aanmaken";
//
// rowLabel
//
this.rowLabel.AutoSize = true;
this.rowLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.rowLabel.Location = new System.Drawing.Point(9, 125);
this.rowLabel.Name = "rowLabel";
this.rowLabel.Size = new System.Drawing.Size(40, 17);
this.rowLabel.TabIndex = 6;
this.rowLabel.Text = "Rijen";
//
// columnLabel
//
this.columnLabel.AutoSize = true;
this.columnLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.columnLabel.Location = new System.Drawing.Point(10, 171);
this.columnLabel.Name = "columnLabel";
this.columnLabel.Size = new System.Drawing.Size(74, 17);
this.columnLabel.TabIndex = 18;
this.columnLabel.Text = "Colommen";
//
// numberLabel
//
this.numberLabel.AutoSize = true;
this.numberLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.numberLabel.Location = new System.Drawing.Point(10, 82);
this.numberLabel.Name = "numberLabel";
this.numberLabel.Size = new System.Drawing.Size(91, 17);
this.numberLabel.TabIndex = 4;
this.numberLabel.Text = "Zaal nummer";
//
// priceLabel
//
this.priceLabel.AutoSize = true;
this.priceLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.priceLabel.Location = new System.Drawing.Point(10, 215);
this.priceLabel.Name = "priceLabel";
this.priceLabel.Size = new System.Drawing.Size(70, 17);
this.priceLabel.TabIndex = 27;
this.priceLabel.Text = "Stoel prijs";
//
// priceInput
//
this.priceInput.DecimalPlaces = 2;
this.priceInput.Location = new System.Drawing.Point(125, 212);
this.priceInput.Name = "priceInput";
this.priceInput.Size = new System.Drawing.Size(495, 20);
this.priceInput.TabIndex = 28;
//
// RoomCreate
//
this.ClientSize = new System.Drawing.Size(1262, 673);
this.Controls.Add(this.panel);
this.Name = "RoomCreate";
this.Controls.SetChildIndex(this.panel, 0);
this.panel.ResumeLayout(false);
this.panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.columnInput)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.rowInput)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numberInput)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.priceInput)).EndInit();
this.ResumeLayout(false);
}
private void SaveButton_Click(object sender, EventArgs e) {
Program app = Program.GetInstance();
ChairService chairManager = app.GetService<ChairService>("chairs");
RoomService roomManager = app.GetService<RoomService>("rooms");
// Create bulk update
BulkUpdate bulkUpdate = new BulkUpdate();
bulkUpdate.Begin();
// Save room
Room room = new Room((int) numberInput.Value);
if (!roomManager.SaveRoom(room)) {
GuiHelper.ShowError(ValidationHelper.GetErrorList(room));
return;
}
// Disable save button
saveButton.Enabled = false;
// Create chairs
int rows = (int) rowInput.Value;
int columns = (int) columnInput.Value;
double price = (double) priceInput.Value;
for (int i = 1; i <= rows; i++) {
for(int j = 1; j <= columns; j++) {
Chair chair = new Chair(room.id, i, j, price, "default");
if (!chairManager.SaveChair(chair)) {
GuiHelper.ShowError(ValidationHelper.GetErrorList(room));
}
}
}
// End bulk update
bulkUpdate.End();
// Enable save button
saveButton.Enabled = true;
// Redirect to screen
RoomDetail roomDetail = app.GetScreen<RoomDetail>("roomDetail");
roomDetail.SetRoom(room);
app.ShowScreen(roomDetail);
GuiHelper.ShowInfo("Zaal succesvol aangemaakt");
}
private void CancelButton_Click(object sender, EventArgs e) {
Program app = Program.GetInstance();
RoomList editScreen = app.GetScreen<RoomList>("roomList");
app.ShowScreen(editScreen);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Lab29.Models;
namespace Lab29.Controllers
{
public class MovieController : ApiController
{
[HttpGet] //1.
public List<Movy> GetAllMovies()
{
MoviesEntities ORM = new MoviesEntities();
return ORM.Movies.ToList();
}
[HttpGet] //2.
public List<Movy> MoviesbyGenre(string Genre)
{
MoviesEntities ORM = new MoviesEntities();
return ORM.Movies.Where(x => x.Genre.Contains(Genre)).ToList();
}
[HttpGet] //3.
public Movy RandomMovie()
{
MoviesEntities ORM = new MoviesEntities();
Random r = new Random();
List<Movy> MovieList = ORM.Movies.ToList();
return MovieList[r.Next(0, MovieList.Count)];
}
[HttpGet] //4.
public Movy RandomMovieCategory(string genre)
{
MoviesEntities ORM = new MoviesEntities();
Random r = new Random();
List<Movy> MovieList = ORM.Movies.ToList();
return ORM.Movies.[r.Next(0, MovieList.Count)];
}
[HttpGet]//5.
public List<Movy>GetRandomMovies(int amount)
{
MoviesEntities ORM = new MoviesEntities();
Random r = new Random();
List<Movy> MovieList = ORM.Movies.ToList();
List<Movy> MovieList2 = new List<Movy>();
for (int i = 0; i < amount; i++)
{
int result = r.Next(MovieList.Count());
MovieList.Add(MovieList2[result]);
MovieList2.RemoveAt(result);
}
return MovieList;
}
[HttpGet]//6.
public List<string> GetAllMovieCategory()
{
MoviesEntities ORM = new MoviesEntities();
return ORM.Movies.Select(x => x.Genre).Distinct().ToList();
}
public Movy Info(string title)
{
MoviesEntities ORM = new MoviesEntities();
}
[HttpGet]
public List<Movy> Keyword(string keyword)
{
MoviesEntities ORM = new MoviesEntities();
return ORM.Movies.Where(x => x.Title.Contains(keyword)).ToList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace moyenne
{
class Program
{
static void Main(string[] args)
{
int n;
do
{
Console.WriteLine("tapez la taille du tableau");
Console.Write(" n= ");
n = int.Parse(Console.ReadLine());
} while (n < 5 || n > 20);
int[] tab = new int[n];
for (int i = 0; i < tab.Length; i++)
{
do
{
Console.WriteLine($"Donnez la valeur de l'élément N° {i+1}");
tab[i] = int.Parse(Console.ReadLine());
}
while (tab[i] % 2 != 0);
}
Console.WriteLine("----------------------------------------------");
Console.WriteLine("les éléments données sont ");
for (int i = 0; i < tab.Length; i++)
{
Console.Write(tab[i] + "|");
}
Console.Write("\n");
Console.WriteLine("----------------------------------------------");
int somme = 0;
for (int i = 0; i < tab.Length; i++)
{
somme += tab[i];
}
double moyenne = somme / n;
Console.WriteLine("la moyenne du tableau est " + moyenne);
Console.ReadKey();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour {
public List<ItemInstance> items;
public ItemInstance GetCurrenItem(Item item) {
return this.items.Find(inst => inst.item == item);
}
public void AddItem(ItemInstance inst) {
var curr = this.GetCurrenItem(inst.item);
if (curr == null) {
this.items.Add(inst);
} else {
curr.amount += inst.amount;
}
}
public void RemoveItem(ItemInstance inst) {
var curr = this.GetCurrenItem(inst.item);
if (curr != null) {
curr.amount -= inst.amount;
if (curr.amount <= 0)
this.items.Remove(curr);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApp.Data.Models
{
public class UserResponseModel
{
public Guid Id { get; set; }
public string Email { get; set; }
public Permissions Permission { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.