text stringlengths 13 6.01M |
|---|
using Microsoft.EntityFrameworkCore.Migrations;
namespace pokemonapp.Migrations
{
public partial class inicial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Pokemones",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Nombre = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Pokemones", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Regiones",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Nombre = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Regiones", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Tipo",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Nombre = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Tipo", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Pueblos",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Nombre = table.Column<string>(type: "nvarchar(max)", nullable: true),
RegionId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Pueblos", x => x.Id);
table.ForeignKey(
name: "FK_Pueblos_Regiones_RegionId",
column: x => x.RegionId,
principalTable: "Regiones",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "PokemonTipo",
columns: table => new
{
PokemonesId = table.Column<int>(type: "int", nullable: false),
TiposId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PokemonTipo", x => new { x.PokemonesId, x.TiposId });
table.ForeignKey(
name: "FK_PokemonTipo_Pokemones_PokemonesId",
column: x => x.PokemonesId,
principalTable: "Pokemones",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_PokemonTipo_Tipo_TiposId",
column: x => x.TiposId,
principalTable: "Tipo",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Entrenadores",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Nombre = table.Column<string>(type: "nvarchar(max)", nullable: true),
PuebloId = table.Column<int>(type: "int", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Entrenadores", x => x.Id);
table.ForeignKey(
name: "FK_Entrenadores_Pueblos_PuebloId",
column: x => x.PuebloId,
principalTable: "Pueblos",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Entrenadores_PuebloId",
table: "Entrenadores",
column: "PuebloId");
migrationBuilder.CreateIndex(
name: "IX_PokemonTipo_TiposId",
table: "PokemonTipo",
column: "TiposId");
migrationBuilder.CreateIndex(
name: "IX_Pueblos_RegionId",
table: "Pueblos",
column: "RegionId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Entrenadores");
migrationBuilder.DropTable(
name: "PokemonTipo");
migrationBuilder.DropTable(
name: "Pueblos");
migrationBuilder.DropTable(
name: "Pokemones");
migrationBuilder.DropTable(
name: "Tipo");
migrationBuilder.DropTable(
name: "Regiones");
}
}
}
|
/*
* Interface for Factories that makes Room.
* e.g.
* RawRoomFactory: makes room based on raw manual string
* XMLRoomFactory: makes room based on XML file
* Copyright (c) Yulo Leake 2016
*/
using Deadwood.Model.Rooms;
namespace Deadwood.Model.Factories
{
interface IRoomFactory
{
Room CreateRoom(string roomname); // Constuct room based on given name
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Labyrinth
{
public static class Save
{
private static string pathBestTime = @"C:\Users\Jorge\Desktop\Labyrinth\Labyrinth-Escape-\Labyrinth\Content\BestScore.txt";
public static void SaveBestTime(string info)
{
using(StreamWriter outputFile = new StreamWriter(Path.GetFullPath(pathBestTime)))
{
outputFile.WriteLine(info);
}
}
public static void LoadBestTime()
{
C.bestTime = (int)Convert.ToDouble(File.ReadAllLines(pathBestTime).GetValue(0).ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace learn_180522_webservice
{
[DataContract]
public class ResultModel
{
[DataMember]
public bool result { get; set; }
[DataMember]
private string dateTime;
public DateTime GetDateTime
{
get
{
return DateTime.ParseExact(this.dateTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
}
set
{
this.dateTime = value.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
}
}
[DataMember]
public string remark { get; set; }
public static ResultModel GteRemark(bool GResult, DateTime GdateTime, string GRemark)
{
ResultModel resmod = new ResultModel();
resmod.result = GResult;
resmod.GetDateTime = GdateTime;
resmod.remark = GRemark;
return resmod;
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using WebAPITest.Models;
namespace WebAPITest.Data
{
public class ProductDbContext : DbContext
{
public ProductDbContext(DbContextOptions<ProductDbContext>options):base(options)
{
}
public DbSet<Product> Products { get; set; }
}
}
|
/**
* Author: János de Vries
* Date: Sep. 2014
* Student Number: 208418
**/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Drawing;
using System.Diagnostics;
namespace ThreadCollor
{
/// <summary>
/// This class is used to calculate the RGB values of each task and report it back to a FileEntry
/// </summary>
class ColorCalculator : BackgroundWorker
{
//A reference to the ListView
private ListView listView_overview;
//A reference to the FileManager
private FileManager fileManager;
//
KeyValuePair<FileEntry, Point> task;
//A reference to the current FileEntry
private FileEntry entry;
//The range of pixel's in the FileEntry that have to be calculated (in height)
private Point range;
//A lock for the getTask() method
private object taskLock;
//An event handler to tell the ThreadManager there is no work left to be done
public event DoneHandler Done;
public delegate void DoneHandler(ColorCalculator c, EventArgs e);
/// <summary>
/// Constructor of the ColorCalculater
/// </summary>
/// <param name="listView_overview">The ListView in which progress will be written</param>
/// <param name="fileManager">The FileManager from which tasks will be gotten</param>
public ColorCalculator(ListView listView_overview, FileManager fileManager, int core, object taskLock)
{
//Set the FileManager
this.fileManager = fileManager;
//Set the ListView
this.listView_overview = listView_overview;
//Set the taskLock
this.taskLock = taskLock;
//Enable progress reporting
WorkerReportsProgress = true;
Monitor.Enter(taskLock);
try
{
if (fileManager.FilesWaiting > 0)
{
task = fileManager.getTask();
}
}
finally { Monitor.Exit(taskLock); }
////Support Cancellation
//WorkerSupportsCancellation = true;
}
/// <summary>
/// The method that runs when the thread has started
/// </summary>
protected override void OnDoWork(DoWorkEventArgs e)
{
//If a FileEntry has been set
if(task.Key != null)
{
//Variable for the Bitmap image
Bitmap image;
//Save the entry and ranged
entry = task.Key;
range = task.Value;
//Create variables to store the average colors
double avgRed = -1,
avgGreen = -1,
avgBlue = -1;
try
{
//Try to load the image
image = new Bitmap(entry.getFilePath());
}
catch(System.ArgumentException) //not an image
{
entry.setStatus("Finished");
return;
}
//Create an instance of the LockBitmap Class
LockBitmap lbm = new LockBitmap(image);
//Lock the image into memory
lbm.LockBits();
//If the pixel range is empty
if (range == Point.Empty)
{
//Calculate all rows within the image
range = new Point(0, image.Height);
}
//Calculate the number of pixels in the image
int numberOfPixels = (range.Y - range.X) * image.Width;
//Set the number of rows calculated to 0
int rowsDone = 0;
//Set the progress to 0
ReportProgress(0);
//For every row of pixels
for (int y = range.X; y < range.Y; y++)
{
//For every column of pixels
for (int x = 0; x < image.Width; x++)
{
//Get the pixel data
Color pixel = lbm.GetPixel(x, y);
//Add the colors to the average
avgRed += pixel.R;
avgGreen += pixel.G;
avgBlue += pixel.B;
}
//Increase the rows done
rowsDone++;
//Every 50th row report progress
if (y % 50 == 0 || y == range.Y - 1)
{
//Calculate the progress
int progress = rowsDone * image.Width;
//Add the progress to the entry
entry.addProgress(progress);
//Reset the rows calculated back to 0
rowsDone = 0;
//Report the entry's progress to the ListView
ReportProgress((int)progress);
}
}
//Calculate the average values and send them to the FileEntry
if (avgRed != -1 && avgGreen != -1 && avgBlue != -1)
{
entry.setRed((avgRed + 1) / numberOfPixels);
entry.setGreen((avgGreen + 1) / numberOfPixels);
entry.setBlue((avgBlue + 1) / numberOfPixels);
}
}
}
/// <summary>
/// This method is called when the progress has been changed
/// </summary>
protected override void OnProgressChanged(ProgressChangedEventArgs e)
{
//If there is an active FileEntry
if(entry != null)
{
//Write the progress to the ListView
listView_overview.Items[entry.getEntryNumber()].SubItems[3].Text = entry.getStatus();
}
}
/// <summary>
/// This method is called when the thread reaches the end of OnDoWork()
/// </summary>
protected override void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
//If the thread has a current FileEntry
if(entry != null)
{
//If it's status is Finished
if(entry.getStatus() == "Finished")
{
//Get a local reference to SubItems
System.Windows.Forms.ListViewItem.ListViewSubItemCollection subItems = listView_overview.Items[entry.getEntryNumber()].SubItems;
//Set all the information in the ListView
subItems[3].Text = "Finished";
subItems[4].Text = entry.getRed();
subItems[5].Text = entry.getGreen();
subItems[6].Text = entry.getBlue();
//Grab the hex value from the entry
string hexValue = entry.getHex();
subItems[7].Text = hexValue;
//If the hex value is not null (visually represented by "-")
if (hexValue != "-")
{
//Color the background of the cell
subItems[8].BackColor = ColorTranslator.FromHtml("#" + hexValue);
//Remove the text placeholder
subItems[8].Text = String.Empty;
}
//Set the entry to null
entry = null;
}
}
//Enter the critical section, lock the lock
Monitor.Enter(this.taskLock);
try
{
//If there is still work left to be done
if (fileManager.FilesWaiting > 0)
{
//Grab a new task
task = fileManager.getTask();
//Start again
this.RunWorkerAsync();
}
//Else all the work is done
else
{
//Report to the thread manager this thread has nothing left to do
Done(this, e);
}
}
finally { Monitor.Exit(taskLock); } //Leave the critical section
}
}
} |
using GeoAPI.Extensions.Coverages;
using GeoAPI.Geometries;
using NetTopologySuite.Extensions.Coverages;
using SharpMap.UI.Forms;
using SharpMap.Layers;
using GeoAPI.Extensions.Feature;
using SharpMap.Styles;
using SharpMap.UI.Tools;
namespace SharpMap.UI.Editors
{
public class FeatureEditorFactory
{
public static IFeatureEditor Create(ICoordinateConverter coordinateConverter, ILayer layer, IFeature feature, VectorStyle vectorStyle)
{
if (null == feature)
return null;
// most specific type should be first
if (feature is CoverageProfile)
return new GridProfileEditor(coordinateConverter, layer, feature, vectorStyle, new DummyEditableObject());
if (feature is RegularGridCoverageCell)
return new RegularGridCoverageCellEditor(coordinateConverter, layer, feature, vectorStyle, new DummyEditableObject());
if (feature is IGridFace || feature is IGridVertex)
return new LineStringEditor(coordinateConverter, layer, feature, vectorStyle, new DummyEditableObject());
if (feature.Geometry is ILineString)
return new LineStringEditor(coordinateConverter, layer, feature, vectorStyle, new DummyEditableObject());
if (feature.Geometry is IPoint)
return new PointEditor(coordinateConverter, layer, feature, vectorStyle, new DummyEditableObject());
// todo implement custom mutator for Polygon and MultiPolygon
// LineStringMutator will work as long as moving is not supported.
if (feature.Geometry is IPolygon)
return new LineStringEditor(coordinateConverter, layer, feature, vectorStyle, new DummyEditableObject());
if (feature.Geometry is IMultiPolygon)
return new LineStringEditor(coordinateConverter, layer, feature, vectorStyle, new DummyEditableObject());
return null;
//throw new ArgumentException("Unsupported type " + feature.Geometry);
}
}
} |
using AtomosZ.Cubeshots.WeaponSystems;
using UnityEngine;
namespace AtomosZ.Cubeshots.WeaponSystems
{
public class FireBullet : MonoBehaviour
{
public GameObject bulletPrefab;
public Vector3 bulletSpawnOffset;
public float cooldown = .25f;
[HideInInspector]
public BasicBullet[] bulletStore;
int bulletCount = 20;
private int nextBulletIndex = 0;
private float timeFired;
void Start()
{
bulletStore = new BasicBullet[bulletCount];
for (int i = 0; i < bulletCount; ++i)
{
bulletStore[i] = Instantiate(bulletPrefab, transform.position, Quaternion.identity).GetComponent<BasicBullet>();
}
}
public void Fire()
{
//if (Time.time - timeFired < cooldown)
// return;
BasicBullet bullet = GetNextBullet();
if (bullet == null)
return;
bullet.Fire(transform.position + bulletSpawnOffset, -transform.right, 0);
timeFired = Time.time;
}
private BasicBullet GetNextBullet()
{
bool restarted = false;
while (bulletStore[nextBulletIndex].enabled)
{
if (++nextBulletIndex >= bulletCount)
{
nextBulletIndex = 0;
if (restarted)
{
Debug.Log(name + " needs bigger bullet store");
return null;
//return Instantiate(bulletPrefab, transform.position, Quaternion.identity).GetComponent<BasicBullet>();
}
restarted = true;
}
}
return bulletStore[nextBulletIndex];
}
}
} |
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using needle.EditorPatching;
using UnityEditor;
using UnityEngine;
namespace Needle.Demystify
{
// ReSharper disable once UnusedType.Global
public class Patch_ConsoleWindowMenuItem : EditorPatchProvider
{
protected override void OnGetPatches(List<EditorPatch> patches)
{
patches.Add(new Patch());
}
private class Patch : EditorPatch
{
protected override Task OnGetTargetMethods(List<MethodBase> targetMethods)
{
var method = Patch_Console.ConsoleWindowType.GetMethod("AddItemsToMenu", BindingFlags.Public | BindingFlags.Instance);
targetMethods.Add(method);
return Task.CompletedTask;
}
// ReSharper disable once UnusedMember.Local
private static void Postfix(GenericMenu menu)
{
const string prefix = "Demystify/";
menu.AddItem(new GUIContent(prefix + "Code Preview"), DemystifySettings.instance.AllowCodePreview,
data => { DemystifySettings.instance.AllowCodePreview = !DemystifySettings.instance.AllowCodePreview; }, null);
menu.AddItem(new GUIContent(prefix + "Short Hyperlinks"), DemystifySettings.instance.ShortenFilePaths,
data => { DemystifySettings.instance.ShortenFilePaths = !DemystifySettings.instance.ShortenFilePaths; }, null);
menu.AddItem(new GUIContent(prefix + "Show Filename"), DemystifySettings.instance.ShowFileName,
data => { DemystifySettings.instance.ShowFileName = !DemystifySettings.instance.ShowFileName; }, null);
menu.AddItem(new GUIContent(prefix + "Auto Filter"), DemystifySettings.instance.AutoFilter,
data => { DemystifySettings.instance.AutoFilter = !DemystifySettings.instance.AutoFilter; }, null);
}
}
}
} |
namespace BettingSystem.Application.Identity
{
using System.Threading.Tasks;
using Commands;
using Commands.ChangePassword;
using Common;
public interface IIdentity
{
Task<Result<IUser>> Register(UserRequestModel userRequest);
Task<Result<UserResponseModel>> Login(UserRequestModel userRequest);
Task<Result> ChangePassword(ChangePasswordRequestModel changePasswordRequest);
}
}
|
using System;
namespace ShapeCalculator
{
public class ShapeAreaCalculator
{
private double _width;
private double _height;
private double _radius;
public double Radius
{
get
{
return _radius;
}
set
{
_radius = value;
}
}
public double Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
public double Height
{
get
{
return _height;
}
set
{
_height = value;
}
}
public ShapeAreaCalculator(double width, double height)
{
_width = width;
_height = height;
}
public ShapeAreaCalculator(double radius)
{
_radius = radius;
}
public double GetRecArea()
{
double area = _width * _height;
return area;
}
public double GetCirArea()
{
double area = Math.PI * (Math.Pow(_radius, 2));
return area;
}
}
}
|
using Msit.Telemetry.Extensions.AI;
using Microsoft.ApplicationInsights.DataContracts;
namespace Microsoft.UnifiedPlatform.Service.Telemetry.Client
{
public interface IAppInsightsTelemetryClientWrapper
{
void TrackTrace(TraceTelemetry traceTelemetry);
void TrackException(ExceptionTelemetry exceptionTelemetry);
void TrackEvent(EventTelemetry eventTelemetry);
void TrackMetric(MetricTelemetry metricTelemetry);
void TrackBusinessProcessEvent(BusinessProcessEvent businessProcessEvent);
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GlobalRef : MonoBehaviour
{
// 全局引用
public static GlobalRef s_gr = null;
public GameObject m_playCamera = null;
public Transform m_uiCanvas = null;
public Transform m_sceneCanvas = null;
//private GameObject m_chapterUIRoot = null;
private GameObject m_playUIRoot = null;
private GameObject m_playRoot = null;
/* public GameObject ChapterUIRoot
{
get { return m_chapterUIRoot; }
set { m_chapterUIRoot = value; }
}
*/
public GameObject PlayUIRoot
{
get { return m_playUIRoot; }
set { m_playUIRoot = value; }
}
public GameObject PlayRoot
{
get { return m_playRoot; }
set { m_playRoot = value; }
}
/*public static RoleInfo s_ri = new RoleInfo();
*/
void Start()
{
GameObject NetLogic = GameObject.Find("NetLogic");
if(NetLogic)
{
s_gr = NetLogic.GetComponent<GlobalRef>();
//Object.DontDestroyOnLoad(NetLogic);
}
else
{
Debug.Log("There is no NetLogic object, please check!");
Application.Quit();
}
//InitRoleData();
}
void Update()
{
if(Application.platform == RuntimePlatform.Android)
{
if(Input.GetKey(KeyCode.Escape) || Input.GetKey(KeyCode.Home))
{
Debug.Log("key escape or home clicked, app exit!");
Application.Quit();
}
}
}
/*
private void InitRoleData()
{
if(HasKey ("AccountId"))
{
SceneWelcome.s_accoutId = GetInt ("AccountId");
}
else
{
SceneWelcome.s_accoutId = NGUITools.RandomRange (10000, 20000);
SetInt("AccountId", SceneWelcome.s_accoutId);
}
if(HasKey ("CreateTime_" + SceneWelcome.s_accoutId))
{
s_ri.createTime = GetInt("CreateTime_" + SceneWelcome.s_accoutId);
}
else
{
s_ri.createTime = SceneLevel.TotalSeconds();
SetInt("CreateTime_" + SceneWelcome.s_accoutId, s_ri.createTime);
}
if(HasKey("CurrentExp_" + SceneWelcome.s_accoutId))
{
s_ri.currentExp = GetInt("CurrentExp_" + SceneWelcome.s_accoutId);
}
else
{
s_ri.currentExp = 0;
SetInt("CurrentExp_" + SceneWelcome.s_accoutId, s_ri.currentExp);
}
if(HasKey("CurrentGold_" + SceneWelcome.s_accoutId))
{
s_ri.currentGold = GetInt("CurrentGold_" + SceneWelcome.s_accoutId);
}
else
{
s_ri.currentGold = 1000;
SetInt("CurrentGold_" + SceneWelcome.s_accoutId, s_ri.currentGold);
}
if(HasKey("CurrentDiamond_" + SceneWelcome.s_accoutId))
{
s_ri.currentDiamond = GetInt("CurrentDiamond_" + SceneWelcome.s_accoutId);
}
else
{
s_ri.currentDiamond = 0;
SetInt("CurrentDiamond_" + SceneWelcome.s_accoutId, s_ri.currentDiamond);
}
if(HasKey("CurrentPower_" + SceneWelcome.s_accoutId))
{
s_ri.currentPower = GetInt("CurrentPower_" + SceneWelcome.s_accoutId);
}
else
{
s_ri.currentPower = 5;
SetInt("CurrentPower_" + SceneWelcome.s_accoutId, s_ri.currentPower);
}
if(HasKey("PowerCountdownTime_" + SceneWelcome.s_accoutId))
{
s_ri.powerCountdownTime = GetInt("PowerCountdownTime_" + SceneWelcome.s_accoutId);
}
else
{
s_ri.powerCountdownTime = 0;
SetInt("PowerCountdownTime_" + SceneWelcome.s_accoutId, s_ri.powerCountdownTime);
}
if(HasKey("CurrentAnimal_" + SceneWelcome.s_accoutId))
{
s_ri.currentAnimal = (EAnimal)GetInt("CurrentAnimal_" + SceneWelcome.s_accoutId);
s_ri.currentAnimal = EAnimal.ANIMAL_CAT;
}
else
{
s_ri.currentAnimal = EAnimal.ANIMAL_CAT;
SetInt("CurrentAnimal_" + SceneWelcome.s_accoutId, (byte)s_ri.currentAnimal);
}
}
public static string AbsFilePath(string fileName_)
{
return Application.streamingAssetsPath + "/Config/" + fileName_;
}
void Update()
{
if(Application.platform == RuntimePlatform.Android)
{
if(Input.GetKey(KeyCode.Escape))
{
Debug.Log("Escape key clicked, app exit!");
Application.Quit();
}
}
}
*/
public static bool HasKey(string key_)
{
return PlayerPrefs.HasKey (key_);
}
public static string GetString(string key_)
{
return PlayerPrefs.GetString (key_);
}
public static int GetInt(string key_)
{
return PlayerPrefs.GetInt(key_);
}
public static float GetFloat(string key_)
{
return PlayerPrefs.GetFloat(key_);
}
public static void SetString(string key_, string value_)
{
PlayerPrefs.SetString(key_, value_);
}
public static void SetInt(string key_, int value_)
{
PlayerPrefs.SetInt(key_, value_);
}
public static void SetFloat(string key_, float value_)
{
PlayerPrefs.SetFloat(key_, value_);
}
}
|
namespace TripDestination.Test.Routes
{
using System.Web.Routing;
using MvcRouteTester;
using NUnit.Framework;
using Web.MVC;
using Web.MVC.Controllers.Media;
[TestFixture]
public class MediaRouteTests
{
private const string username = "pesho";
private const string guid = "aasdas-232-asd";
private const int size = 480;
[Test]
public void MediaRouteDetailsShouldWorkCorrectly()
{
string Url = string.Format("/Media/Image/{0}/{1}/{2}", username, guid, size);
var routeCollection = new RouteCollection();
RouteConfig.RegisterRoutes(routeCollection);
routeCollection.ShouldMap(Url).To<ImageController>(c => c.Index(username, guid, size));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BizService.Common;
using IWorkFlow.Host;
using IWorkFlow.ORM;
using Newtonsoft.Json;
namespace BizService.Services
{
class B_OA_SupervisionStaticSvc : BaseDataHandler
{
[DataAction("GetCompleteSupervisionStatic", "year", "quarter", "userid")]
public string GetCompleteSupervisionStatic(string year, string quarter, string userid)
{
IDbTransaction tran = Utility.Database.BeginDbTransaction();
StringBuilder strSql = new StringBuilder();
GetDataModel dataModel = new GetDataModel();
StringBuilder whereSql = new StringBuilder();
try
{
string strStartTime = "";
string strEndTime = "";
if (year != "" && quarter != "")
{
CommonFunctional.GetQuarterTime(int.Parse(year), int.Parse(quarter), out strStartTime, out strEndTime);
whereSql.AppendFormat(@"and EndDate >= '{0}' and EndDate<='{1}' ", strStartTime, strEndTime);
}
else if (year != "" && quarter=="")
{
whereSql.AppendFormat(@"and EndDate like '%{0}%'",year);
}
if (whereSql.ToString().Length > 0)
{
strSql.AppendFormat(@"
SELECT ROW_NUMBER() OVER ( PARTITION BY newTb.ID ORDER BY newTb.ReceDate DESC ) AS ROWINDEX ,
newTb.*
INTO #Temp
FROM ( SELECT a.ID ,
b.Remark ,
b.ReceDate,
c.code,
c.title,
c.supervisionManName,
c.undertake_Department,
c.assistDepartment,
a.EndDate
FROM FX_WorkFlowCase AS a
LEFT JOIN FX_WorkFlowBusAct AS b ON b.CaseID = a.ID
LEFT JOIN B_OA_Supervision AS c ON c.caseId = a.ID
WHERE a.IsEnd = '1'
AND ( a.FlowID = 'W000094'
OR a.FlowID = 'W000091'
)
{0}
) newTb
SELECT *
FROM #Temp
WHERE ROWINDEX = 1
DROP TABLE #Temp
", whereSql);
}
else
{
strSql.AppendFormat(@"
SELECT ROW_NUMBER() OVER ( PARTITION BY newTb.ID ORDER BY newTb.ReceDate DESC ) AS ROWINDEX ,
newTb.*
INTO #Temp
FROM ( SELECT a.ID ,
b.Remark ,
b.ReceDate,
c.code,
c.title,
c.supervisionManName,
c.undertake_Department,
c.assistDepartment,
a.EndDate
FROM FX_WorkFlowCase AS a
LEFT JOIN FX_WorkFlowBusAct AS b ON b.CaseID = a.ID
LEFT JOIN B_OA_Supervision AS c ON c.caseId = a.ID
WHERE a.IsEnd = '1'
AND ( a.FlowID = 'W000094'
OR a.FlowID = 'W000091'
)
) newTb
SELECT *
FROM #Temp
WHERE ROWINDEX = 1
DROP TABLE #Temp
");
}
DataSet ds = Utility.Database.ExcuteDataSet(strSql.ToString(), tran);
Utility.Database.Commit(tran);
dataModel.dt = ds.Tables[0];
return JsonConvert.SerializeObject( dataModel);
}
catch (Exception ex)
{
Utility.Database.Rollback(tran);
return Utility.JsonMsg(false, "数据加载失败!异常信息: " + ex.Message);
}
}
[DataAction("GetReminderSupervisionStatic", "year", "quarter", "userid")]
public string GetReminderSupervisionStatic(string year, string quarter, string userid)
{
IDbTransaction tran = Utility.Database.BeginDbTransaction();
StringBuilder strSql = new StringBuilder();
GetDataModel dataModel = new GetDataModel();
StringBuilder whereSql = new StringBuilder();
try
{
string strStartTime = "";
string strEndTime = "";
if (year != "" && quarter != "")
{
CommonFunctional.GetQuarterTime(int.Parse(year), int.Parse(quarter), out strStartTime, out strEndTime);
whereSql.AppendFormat(@"and createDate >= '{0}' and createDate<='{1}' ", strStartTime, strEndTime);
}
else if (year != "" && quarter == "")
{
whereSql.AppendFormat(@" and createDate like '%{0}%'", year);
}
strSql.AppendFormat(@"select undertake_Department,title,code,reminderCount,explain,createDate,caseId from B_OA_SupervisionReminder where 1=1");
if (whereSql.ToString().Length>0)
{
strSql.Append(whereSql);
}
DataSet ds = Utility.Database.ExcuteDataSet(strSql.ToString(), tran);
Utility.Database.Commit(tran);
dataModel.dt = ds.Tables[0];
return JsonConvert.SerializeObject( dataModel);
}
catch (Exception ex)
{
Utility.Database.Rollback(tran);
return Utility.JsonMsg(false, "数据加载失败!异常信息: " + ex.Message);
}
}
public class GetDataModel
{
public DataTable dt;
}
public override string Key
{
get
{
return "B_OA_SupervisionStaticSvc";
}
}
}
}
|
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ConsoleApplication1
{
class UsingCollector:CSharpSyntaxWalker
{
public readonly List<SyntaxNode> Statements = new List<SyntaxNode>();
public List<SyntaxKind> find = new List<SyntaxKind>() {SyntaxKind.IfStatement,SyntaxKind.ElseClause,SyntaxKind.ForEachStatement,SyntaxKind.WhileStatement,SyntaxKind.ForStatement,SyntaxKind.DoStatement,SyntaxKind.SwitchStatement,SyntaxKind.TryStatement};
public override void VisitIfStatement(IfStatementSyntax node)
{
this.Statements.Add(node);
}
public override void VisitSwitchStatement(SwitchStatementSyntax node)
{
this.Statements.Add(node);
}
public override void VisitElseClause(ElseClauseSyntax node)
{
this.Statements.Add(node);
}
public override void VisitWhileStatement(WhileStatementSyntax node)
{
this.Statements.Add(node);
}
public override void VisitForEachStatement(ForEachStatementSyntax node)
{
this.Statements.Add(node);
}
public override void VisitForStatement(ForStatementSyntax node)
{
this.Statements.Add(node);
}
public override void VisitDoStatement(DoStatementSyntax node)
{
this.Statements.Add(node);
}
public override void VisitTryStatement(TryStatementSyntax node)
{
this.Statements.Add(node);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResourcePack : MonoBehaviour {
public static void Load(string pack = null)
{
if(string.IsNullOrEmpty(pack))
{
//Load default
var terrain = Resources.Load<Texture>("default/terrain");
Shader.SetGlobalTexture("_TERRAIN_TEX", terrain);
}
else
{
//Load from folder
}
}
}
|
using System;
using System.Web;
using NHibernate.Cfg;
using NHibernate.Context;
namespace NHibernate.Session
{
public class Marshaler
{
private readonly object _lock = new object();
private readonly Configuration _configuration;
private readonly System.Type _sessionInterceptor;
private readonly bool _useSingletonSession;
private ISessionFactory _factory;
private ISession _singletonSession;
public event SessionFactoryCreated OnSessionFactoryCreated;
public Marshaler(Configuration configuration, System.Type sessionInterceptor, bool useSingletonSession)
{
_configuration = configuration;
_sessionInterceptor = sessionInterceptor;
_useSingletonSession = useSingletonSession;
}
public Marshaler(Configuration configuration, System.Type sessionInterceptor) : this(configuration, sessionInterceptor, false) { }
public Marshaler(Configuration configuration) : this(configuration, null) { }
public bool HasSession
{
get
{
if (_useSingletonSession)
{
lock (_lock)
{
return _factory != null && _singletonSession != null;
}
}
return _factory != null && CurrentSessionContext.HasBind(_factory);
}
}
public IStatelessSession GetStatelessSession()
{
if (_factory != null) return _factory.OpenStatelessSession();
if (_useSingletonSession)
{
lock (_lock)
{
if (_factory != null) return _factory.OpenStatelessSession();
_factory = _configuration.BuildSessionFactory();
var sessionFactoryCreated = OnSessionFactoryCreated;
if (sessionFactoryCreated != null)
{
sessionFactoryCreated.Invoke(this, new SessionFactoryCreatedArgs(_factory));
}
return _factory.OpenStatelessSession();
}
}
if (HttpContext.Current != null)
{
InitializeContextAwareFactory<WebSessionContext>();
}
else
{
InitializeContextAwareFactory<ThreadStaticSessionContext>();
}
if (_factory == null) throw new InvalidOperationException("SessionFactory was not initialized");
return _factory.OpenStatelessSession();
}
public ISession CurrentSession
{
get
{
if (_useSingletonSession)
{
lock (_lock)
{
if (_factory == null)
{
_factory = _configuration.BuildSessionFactory();
var sessionFactoryCreated = OnSessionFactoryCreated;
if (sessionFactoryCreated != null)
{
sessionFactoryCreated.Invoke(this, new SessionFactoryCreatedArgs(_factory));
}
return GetNewSingletonSession();
}
return _singletonSession ?? GetNewSingletonSession();
}
}
if (_factory == null)
{
if (HttpContext.Current != null)
{
InitializeContextAwareFactory<WebSessionContext>();
}
else
{
InitializeContextAwareFactory<ThreadStaticSessionContext>();
}
}
if (_factory == null) throw new InvalidOperationException("SessionFactory was not initialized");
if (CurrentSessionContext.HasBind(_factory)) return _factory.GetCurrentSession();
var session = (_sessionInterceptor == null) ? _factory.OpenSession() : _factory.OpenSession((IInterceptor)Activator.CreateInstance(_sessionInterceptor));
session.BeginTransaction();
CurrentSessionContext.Bind(session);
return session;
}
}
private ISession GetNewSingletonSession()
{
_singletonSession = (_sessionInterceptor == null) ? _factory.OpenSession() : _factory.OpenSession((IInterceptor)Activator.CreateInstance(_sessionInterceptor));
_singletonSession.BeginTransaction();
return _singletonSession;
}
private void InitializeContextAwareFactory<T>() where T : ICurrentSessionContext
{
if (_factory != null) return;
lock (_lock)
{
if (_factory != null) return;
_factory = _configuration.CurrentSessionContext<T>().BuildSessionFactory();
var sessionFactoryCreated = OnSessionFactoryCreated;
if (sessionFactoryCreated != null)
{
sessionFactoryCreated.Invoke(this, new SessionFactoryCreatedArgs(_factory));
}
}
}
public void Commit()
{
if (_useSingletonSession)
{
lock (_lock)
{
if (_factory == null) return;
if (_singletonSession == null) return;
try
{
_singletonSession.Flush();
_singletonSession.Transaction.Commit();
_singletonSession.Transaction.Begin();
}
catch (Exception)
{
if (_singletonSession != null
&& _singletonSession.Transaction != null
&& !_singletonSession.Transaction.WasCommitted
&& !_singletonSession.Transaction.WasRolledBack)
{
_singletonSession.Transaction.Rollback();
}
if(_singletonSession != null && _singletonSession.IsOpen)
{
_singletonSession.Close();
}
throw;
}
}
}
else
{
if (_factory == null) return;
if (!CurrentSessionContext.HasBind(_factory)) return;
try
{
_factory.GetCurrentSession().Flush();
_factory.GetCurrentSession().Transaction.Commit();
if (HttpContext.Current == null)
{
_factory.GetCurrentSession().Transaction.Begin();
}
}
catch (Exception)
{
if (_factory.GetCurrentSession() != null
&& _factory.GetCurrentSession().Transaction != null
&& !_factory.GetCurrentSession().Transaction.WasCommitted
&& !_factory.GetCurrentSession().Transaction.WasRolledBack)
{
_factory.GetCurrentSession().Transaction.Rollback();
}
var session = CurrentSessionContext.Unbind(_factory);
if(session != null && session.IsOpen)
{
session.Close();
}
throw;
}
}
}
public void End()
{
if (_useSingletonSession)
{
lock (_lock)
{
if (_factory == null) return;
if (_singletonSession == null) return;
_singletonSession.Close();
}
}
else
{
if (_factory == null) return;
if (!CurrentSessionContext.HasBind(_factory)) return;
var session = CurrentSessionContext.Unbind(_factory);
session.Close();
}
}
}
} |
using MonitorBoletos.Business;
using MonitorBoletos.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using BoletoNet;
using Semafaro.Titulos.Model;
using Semafaro.Titulos.Business;
using System.Linq;
using MonitorBoletos.Util;
using System.Data;
namespace MonitorBoletos.DesktopView
{
public partial class FrmPrincipal : Form
{
#region Construtor
public FrmPrincipal()
{
InitializeComponent();
}
private const string V = "2";
#endregion
#region Campos
ArquivoRetornoCNAB400 cnab400 = new BoletoNet.ArquivoRetornoCNAB400();
ArquivoRetornoCNAB240 cnab240 = new ArquivoRetornoCNAB240();
List<OcorrenciaCobranca> outrasOcorrencias = new List<OcorrenciaCobranca>();
List<OcorrenciaCobranca> NossoNumeroNaoEncontado = new List<OcorrenciaCobranca>();
Guid guid;
string[] listaNumeros;
#endregion
#region Eventos
/// <summary>
/// Processa o arquivo de retorno
/// </summary>
private bool LerArquivoRetorno()
{
try
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Arquivos de Retorno (*.ret;*.crt)|*.ret;*.crt|Todos Arquivos (*.*)|*.*";
openFile.Title = "Selecione um arquivo!";
openFile.InitialDirectory = @"C:\Users\joao.goncalves\Desktop\XML";
//se o dialogo retornar OK
if (openFile.ShowDialog() == DialogResult.OK)
{
txtMsg.Text = openFile.FileName;
//verifica se o arquivo existe
if (openFile.CheckFileExists == true)
{
try
{
using (var bussBanco = new BancoBusiness())
{
var cbItem = cbBancos.SelectedValue;
var banco = bussBanco.ObterPorID(cbItem);
//lê o arquivo de retorno
using (var bussArquivo = new ArquivoBusiness())
{
var tipo = bussArquivo.verificaTipoCNAB(openFile.FileName);
return bussArquivo.lerArquivoRetorno(banco, openFile.OpenFile(), tipo);
}
}
}
catch (Exception)
{
throw;
}
}
}
return false;
}
catch (Exception ex)
{
throw ex;
}
}
private bool LerArquivoRetorno(OpenFileDialog openFile)
{
try
{
using (var bussBanco = new BancoBusiness())
{
var cbItem = cbBancos.SelectedValue;
var banco = bussBanco.ObterPorID(cbItem);
foreach (var item in openFile.FileNames)
{
var stream = new FileStream(item, FileMode.Open, FileAccess.Read);
//lê o arquivo de retorno
using (var bussArquivo = new ArquivoBusiness())
{
var tipo = bussArquivo.verificaTipoCNAB(item);
bussArquivo.lerArquivoRetorno(banco, stream, tipo);
}
}
return true;
}
}
catch (Exception ex)
{
throw ex;
}
}
private bool LerArquivosRetorno()
{
try
{
OpenFileDialog openFile = new OpenFileDialog
{
Filter = "Arquivos de Retorno (*.ret;*.crt)|*.ret;*.crt|Todos Arquivos (*.*)|*.*",
Title = "Selecione um arquivo!",
//InitialDirectory = @"C:\Users\joao.goncalves\Desktop\XML",
Multiselect = true
};
if (openFile.ShowDialog() == DialogResult.OK)
{
if (openFile.CheckFileExists == true)
{
return LerArquivoRetorno(openFile);
}
}
}
catch (Exception)
{
throw;
}
return false;
}
/// <summary>
/// Envia o arquivo para ser processado
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void btEnviar_Click(object sender, EventArgs e)
{
if (LerArquivoRetorno())
{
atualizarGridView();
MessageBox.Show("Leitura realizada com sucesso!", "Arquivo Retorno", MessageBoxButtons.OK, MessageBoxIcon.Information);
//btProcessarArquivoCronn.Enabled = true;
}
else
{
MessageBox.Show("Não foi possivel ler o arquivo", "Arquivo Retorno", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
#endregion
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
new FrmCadastroBanco().Show();
}
/// <summary>
/// Metodos executados ao carregar o formulario
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmPrincipal_Load(object sender, EventArgs e)
{
atualizarComboBanco();
atualizarGridView();
}
/// <summary>
/// Ao clicar no botão atualizar
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lnkAtualizarCbBancos_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
atualizarComboBanco();
atualizarGridView();
}
private void atualizarGridView()
{
using (var bc = new ArquivoBusiness())
{
dataGridView1.DataSource = bc.ObterTodos();
dataGridView1.Columns["OcorrenciasCobranca"].Visible = false;
}
}
/// <summary>
/// Atualizando o combo com os registros já cadastrados
/// </summary>
private void atualizarComboBanco()
{
using (BancoBusiness bc = new BancoBusiness())
{
cbBancos.DataSource = bc.ObterTodos();
cbBancos.DisplayMember = "Descricao";
cbBancos.ValueMember = "Id";
}
}
private async void btProcessarArquivoCronn_Click(object sender, EventArgs e)
{
var arquivo = new Arquivo();
using (ArquivoBusiness arquivoBuss = new ArquivoBusiness())
{
arquivo = arquivoBuss.ObterPorId(guid);
}
processarArquivoCronn_PRD_SgvCobranca(arquivo);
}
/// <summary>
/// Processa o arquivo na base Cronn_PRD
/// </summary>
private void processarArquivoCronn_PRD_SgvCobranca(Arquivo arquivo)
{
//Separa as ocorrencias e mostra a quantidade de cada
var tipos_ocorrencia = from b in arquivo.OcorrenciasCobranca
group b by b.CodigoOcorrencia into grupo
select new { id = grupo.Key, qtde = grupo.Count() };
//Cria uma lista de ocorrencias do tipo 6 e 17 "Pagamento"
var pagos = arquivo.OcorrenciasCobranca.Where(p => p.CodigoOcorrencia.Trim().Equals("6") || p.CodigoOcorrencia.Trim().Equals("17"));
listBoxMsg.Items.Add(string.Format(arquivo.Nome));
listBoxMsg.Items.Add(string.Format($"A quantidade TOTAL de registros é {arquivo.OcorrenciasCobranca.Count()}"));
listBoxMsg.Items.Add(string.Format($"A quantidade TOTAL de boletos pagos: {pagos.Count()}"));
//Joga na List o resultado da pesquisa
foreach (var item in tipos_ocorrencia)
{
listBoxMsg.Items.Add(string.Format($"A quantidade de registros do tipo {item.id} é de: {item.qtde}"));
Console.WriteLine($"A quantidade de registros do tipo {item.id} é {item.qtde}");
}
Console.WriteLine($"A quantidade TOTAL de registros é {arquivo.OcorrenciasCobranca.Count()}");
//cria uma instancia um objeto do tipo CronnSgvCobranca
var sgvCobranca = new CronnSgvCobranca();
//cria uma lista com esses objetos criados
var ListCronnSgvCobranca = new List<CronnSgvCobranca>();
//cria uma instancia do CronnBusiness
var cronnbs = new CronnSgvCobrancaBusiness();
//cria uma instancia do MBSVC
var ws = new MBSVC.DefaultSoapClient();
//var ListaNossoNumero = from n in pagos
// select new { n.NossoNumero }.NossoNumero;
var ListaNossoNumero = new List<string>();
foreach (var item in pagos)
{
ListaNossoNumero.Add(item.NossoNumero);
}
listaNumeros = ListaNossoNumero.ToArray();
try
{
//ListCronnSgvCobranca = cronnbs.ObterTodasCobrancas(ListaNossoNumero);
var cronnSgvCobrancas = ws.ObterListaTitulos(listaNumeros);
var group = from b in cronnSgvCobrancas
group b by b.TipoCobranca into grp
select new { key = grp.Key, cnt = grp.Count() };
foreach (var item in group)
{
switch (item.key)
{
case 0:
listBoxMsg.Items.Add(string.Format($"Quantidade de PosPago: {item.cnt}"));
Console.WriteLine($"Quantidade de PosPago: {item.cnt}");
break;
case 1:
listBoxMsg.Items.Add(string.Format($"Quantidade de PréPago: {item.cnt}"));
Console.WriteLine($"Quantidade de PréPago: {item.cnt}");
break;
}
}
}
catch (Exception ex)
{
throw new Exception("Erro ao consultar o banco de dados", ex.InnerException);
}
var listNumeroNaoEncontrado = cronnbs.NumerosNaoEncontrados(ListaNossoNumero);
if (listNumeroNaoEncontrado != null)
{
foreach (var item in listNumeroNaoEncontrado)
{
listBoxMsg.Items.Add(string.Format($"NossoNumero não encontrado na base de dados: {item}"));
}
}
listBoxMsg.Items.Add(string.Empty);
resetarBotoes();
btSendEmail.Enabled = true;
}
private void resetarBotoes()
{
btProcessarArquivoCronn.Enabled = false;
txtMsg.Clear();
btSendEmail.Enabled = false;
}
private void btSendEmail_Click(object sender, EventArgs e)
{
var listItens = new List<string>();
foreach (var item in listBoxMsg.Items)
{
listItens.Add(item.ToString());
}
var arquivo = new SendEmails();
try
{
arquivo.SendMail(listItens);
MessageBox.Show("E-mail enviado com sucesso!");
}
catch (Exception)
{
throw;
}
resetarBotoes();
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
var linhaGrid = dataGridView1.Rows[e.RowIndex];
var id = (Guid)linhaGrid.Cells["Id"].Value;
new FrmListaOcorrencia(id).Show();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var linhaGrid = dataGridView1.Rows[e.RowIndex];
var id = (Guid)linhaGrid.Cells["Id"].Value;
guid = id;
btProcessarArquivoCronn.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
//var svc = new MBSVC.DefaultSoapClient();
//var result = svc.FazerAlgo();
//var lista = svc.ObterListaTitulos(listaNumeros);
}
private void button2_Click(object sender, EventArgs e)
{
//LerArquivosRetorno();
if (LerArquivosRetorno())
{
atualizarGridView();
MessageBox.Show("Leitura realizada com sucesso!", "Arquivo Retorno", MessageBoxButtons.OK, MessageBoxIcon.Information);
//btProcessarArquivoCronn.Enabled = true;
}
else
{
MessageBox.Show("Não foi possivel ler o arquivo", "Arquivo Retorno", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void btCalcularQuantidadeTotal_Click(object sender, EventArgs e)
{
calcularQuantidadeTotalPorEmpresa();
}
private void calcularQuantidadeTotalPorEmpresa()
{
listBoxMsg.Items.Clear();
using (var todos = new ArquivoBusiness())
{
var arquivos = (List<Arquivo>)todos.ObterTodos();
var log = new List<ContadorPorEmpresa>();
var rdc = new List<ContadorPorEmpresa>();
var drj = new List<ContadorPorEmpresa>();
List<ContadorPorEmpresa> contarPorQuantidade(Arquivo arquivo)
{
var ListaContadorEmpresa = new List<ContadorPorEmpresa>();
//Separa as ocorrencias e mostra a quantidade de cada
var tipos_ocorrencia = from b in arquivo.OcorrenciasCobranca
group b by b.CodigoOcorrencia into grupo
select new { id = grupo.Key, qtde = grupo.Count() };
foreach (var item in tipos_ocorrencia)
{
var contadorEmpresa = new ContadorPorEmpresa();
contadorEmpresa.TipoOcorrencia = item.id;
contadorEmpresa.Quantidade = item.qtde;
var valores = arquivo.OcorrenciasCobranca
.Where(x => x.CodigoOcorrencia == item.id)
.Select(g => new
{
Valor = g.ValorTitulo,
Pago = g.ValorPago
});
contadorEmpresa.ValorTitulo = valores.Sum(x => x.Valor);
contadorEmpresa.ValorPago = valores.Sum(x => x.Pago);
ListaContadorEmpresa.Add(contadorEmpresa);
}
return ListaContadorEmpresa;
//Separa as ocorrencias e mostra a quantidade e valorpago de cada
//var contador = arquivo.OcorrenciasCobranca
// .GroupBy(y => y.CodigoOcorrencia)
// .Select(grop => new
// {
// CodigoOcorrencia = grop.Key,
// Quantidade = grop.Count(),
// ValorPago = grop.Sum(valor => valor.ValorPago)
// });
//var resultados = new List<ContadorPorEmpresa>();
//foreach (var item in contador)
//{
// var result = new ContadorPorEmpresa();
// result.TipoOcorrencia = item.CodigoOcorrencia;
// result.Quantidade = item.Quantidade;
// result.ValorPago = item.ValorPago;
// resultados.Add(result);
//}
//return resultados;
}
foreach (var item in arquivos)
{
if (item.Nome.Trim().ToUpper().Contains("LOG"))
{
var contar = contarPorQuantidade(item);
foreach (var count in contar)
{
log.Add(count);
}
}
else if (item.Nome.Trim().ToUpper().Contains("RDC"))
{
var contar = contarPorQuantidade(item);
foreach (var count in contar)
{
rdc.Add(count);
}
}
else if (item.Nome.Trim().ToUpper().Contains("DRJ"))
{
var contar = contarPorQuantidade(item);
foreach (var count in contar)
{
drj.Add(count);
}
}
}
resultado(log, "LOG");
resultado(rdc, "RDC");
resultado(drj, "DRJ");
void resultado(List<ContadorPorEmpresa> empresa, string nomeEmpresa)
{
var tipos_ocorrencia = from b in empresa
group b by b.TipoOcorrencia into grupo
select new { id = grupo.Key, qtde = grupo.Count() };
var result = empresa
.GroupBy(b => b.TipoOcorrencia)
.Select(group => new
{
id = group.Key,
qtda = group.Sum(x => x.Quantidade),
valorTitulo = group.Sum(x => x.ValorTitulo),
valorPago = group.Sum(x => x.ValorPago)
});
//var result = empresa
// .GroupBy(y => y.TipoOcorrencia)
// .Select(grop => new
// {
// CodigoOcorrencia = grop.Key,
// Quantidade = grop.Count(),
// ValorPago = grop.Sum(valor => valor.ValorPago)
// });
listBoxMsg.Items.Add(string.Format($"Empresa {nomeEmpresa}"));
foreach (var itens in result)
{
listBoxMsg.Items.Add(string.Format($"A quantidade de registros do tipo {itens.id} é de: {itens.qtda}, valor do Titulo é de: {itens.valorTitulo} e o Valor Pago é de: {itens.valorPago}"));
}
listBoxMsg.Items.Add(string.Empty);
}
}
}
private void btDeletarTodos_Click(object sender, EventArgs e)
{
var linhaGrid = dataGridView1.Rows;
foreach (var item in linhaGrid)
{
DataGridViewRow Lista = (DataGridViewRow)item;
var id = (Guid)Lista.Cells["Id"].Value;
using (var bc = new ArquivoBusiness())
{
bc.DeletarPorId(id);
}
}
atualizarGridView();
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WebAutomation
{
public partial class WindowsLogon : Form
{
DataGridViewCell activeCell = null;
public WindowsLogon(DataGridViewCell currentCell)
{
activeCell = currentCell;
InitializeComponent();
}
private void btnOkay_Click(object sender, EventArgs e)
{
if (txtUserName.Text.Trim().Length == 0)
{
UIHelper.StopMessage("Please enter the value");
txtUserName.Focus();
return;
}
else if (txtPassword.Text.Trim().Length == 0)
{
UIHelper.StopMessage("Please enter the value");
txtPassword.Focus();
return;
}
activeCell.OwningRow.Cells["Data"].Value = "User name:"+ txtUserName + "Password:" +txtPassword.Text;
}
}
}
|
using System;
using System.Collections.Generic;
using VideoStream.Models;
using VideoStream.ViewModels;
using Xamarin.Forms;
namespace VideoStream.Views
{
public partial class SecondPage : ContentView
{
public SecondPage()
{
InitializeComponent();
BackgroundColor = Color.White;
}
private async void HandleTapped(object sender,EventArgs e)
{
var gestureRecognizer =(sender as StackLayout).GestureRecognizers[0] as TapGestureRecognizer;
var video = gestureRecognizer.CommandParameter as Video;
var MainPageVM = BindingContext as MainPageViewModel;
MainPageVM.PlayVideoCommand.Execute(video);
}
private async void Refreshing(object sender,EventArgs e)
{
var MainPageVM = BindingContext as MainPageViewModel;
MainPageVM.RefreshCommand.Execute(new object());
}
}
}
|
namespace P04TowerOfHanoi
{
using System;
using System.Collections.Generic;
using System.Linq;
public class EntryPoint
{
private static int move;
private static Stack<int> source;
private static readonly Stack<int> destination = new Stack<int>();
private static readonly Stack<int> spare = new Stack<int>();
public static void Main()
{
int n = 5;// int.Parse(Console.ReadLine());
source = new Stack<int>(Enumerable.Range(1, n).Reverse());
PrintPegs();
MoveDisks(n, source, destination, spare);
}
private static void PrintPegs()
{
Console.WriteLine($"Source: {string.Join(", ", source.Reverse())}");
Console.WriteLine($"Destination: {string.Join(", ", destination.Reverse())}");
Console.WriteLine($"Spare: {string.Join(", ", spare.Reverse())}");
Console.WriteLine();
}
private static void MoveDisks(
int bottomDisk,
Stack<int> sourcePeg,
Stack<int> destinationPeg,
Stack<int> sparePeg)
{
if (bottomDisk < 1)
{
return;
}
MoveDisks(bottomDisk - 1, sourcePeg, sparePeg, destinationPeg);
move++;
destinationPeg.Push(bottomDisk);
sourcePeg.Pop();
Console.WriteLine($"Step #{move}: Moved disk");
PrintPegs();
MoveDisks(bottomDisk - 1, sparePeg, destinationPeg, sourcePeg);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
namespace KartObjects.Entities.Documents
{
/// <summary>
/// Состояния чека
/// </summary>
[Serializable]
public enum ReceiptState
{
/// <summary>
/// Чек открыт
/// </summary>
Open = 0,
/// <summary>
/// Оплата прошла, но не вышел фискальный чек
/// </summary>
Hanged = 1,
/// <summary>
/// Чек оформлен
/// </summary>
Printed = 2,
/// <summary>
/// После закрытия чека не удалось получить KPK
/// </summary>
KpkConfirmationUnknown = 3
}
/// <summary>
/// Статус чека
/// </summary>
[Serializable]
public enum ReceiptStatus
{
/// <summary>
/// Чек не пепредан на сервер
/// </summary>
ReadyToSend = 0,
/// <summary>
/// Чек передан на сервер
/// </summary>
OnServer = 1,
/// <summary>
/// По чеку сформировано товародвижение
/// </summary>
Closed = 2
}
/// <summary>
/// Фискальный чек
/// </summary>
[Serializable]
public class Receipt : SimpleDbEntity
{
private int _directOperation;
private ReceiptState _receiptState;
public Receipt()
{
BarcodeList = new List<string>();
ReceiptState = ReceiptState.Open;
DateReceipt = DateTime.Now;
IsBaseReturned = false;
}
/// <summary>
/// Конструктор, генерирующий уникальный идентификатор чека
/// </summary>
/// <param name="idPosDevice">Идентификатор фискальника (кассового устройства)</param>
/// <param name="numShift">Номер смены фискальника</param>
/// <param name="numReceipt">Номер чека фискальника</param>
public Receipt(long idPosDevice, int numShift, int numReceipt)
{
Id = idPosDevice*Convert.ToInt64(1E+10) + numShift*(Convert.ToInt64(1E+6)) +
numReceipt*(Convert.ToInt64(1E+2));
IdPosDevice = idPosDevice;
Number = numReceipt;
ShiftNumber = numShift;
ReceiptSpecRecords = new List<ReceiptSpecRecord>();
Payment = new List<Payment>();
ReceiptState = ReceiptState.Open;
DateReceipt = DateTime.Now;
IsBaseReturned = false;
ReturnCurrShift = false;
}
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public override string FriendlyName
{
get { return "Фискальный чек"; }
}
/// <summary>
/// Номер смены
/// </summary>
public int ShiftNumber { get; set; }
/// <summary>
/// Номер чека в пределах смены
/// </summary>
public int Number { get; set; }
/// <summary>
/// Номер магазина
/// </summary>
public long IdPosDevice { get; set; }
public long IdCashier { get; set; }
[DBIgnoreAutoGenerateParam]
[DBIgnoreReadParam]
[XmlIgnore]
public Cashier Cashier { get; set; }
/// <summary>
/// Номер кпк
/// </summary>
public int KpkNum { get; set; }
public bool IsDeleted { get; set; }
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public List<string> BarcodeList { get; set; }
public DateTime DateReceipt { get; set; }
public DateTime InsertTime { get; set; }
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public string FullNumber
{
get { return IdPosDevice + "." + ShiftNumber + "." + Number; }
set
{
string[] starr = value.Split('.');
if (starr.Length > 2)
{
IdPosDevice = Int32.Parse(starr[0]);
ShiftNumber = Int32.Parse(starr[1]);
Number = Int32.Parse(starr[2]);
}
}
}
/// <summary>
/// Направление операции, возврат или нет
/// </summary>
public int DirectOperation
{
get { return _directOperation; }
set
{
if ((value == 1) || (value == -1))
_directOperation = value;
else
{
_directOperation = 1;
throw new Exception("Неверное значение направления операции!!!");
}
}
}
[DBIgnoreReadParam]
public string ReturnReceiptNumber { get; set; }
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public bool ReturnCurrShift { get; set; }
/// <summary>
/// Состояние чека
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public ReceiptState ReceiptState
{
get { return _receiptState; }
set
{
if (value == ReceiptState.Printed)
//Рассчитываем скидку на тип оплаты
ApplyPaymentDiscount();
_receiptState = value;
}
}
[DBIgnoreReadParam]
public ReceiptStatus ReceiptStatus { get; set; }
/// <summary>
/// Спецификация чека
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public List<ReceiptSpecRecord> ReceiptSpecRecords { get; set; }
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public List<Payment> Payment { get; set; }
/// <summary>
/// Сумма чека
/// </summary>
[DBIgnoreReadParam]
public decimal TotalSum
{
get
{
if (ReceiptSpecRecords != null)
{
IEnumerable<decimal> q = from e in ReceiptSpecRecords
where e.IsDeleted == false
select e.PosSum;
return Convert.ToDecimal(q.Sum());
}
return 0;
}
}
/// <summary>
/// Сумма скидки
/// </summary>
[DBIgnoreReadParam]
public decimal TotalDiscount
{
get
{
if (ReceiptSpecRecords != null)
{
IEnumerable<decimal> q = from e in ReceiptSpecRecords
where e.IsDeleted == false
select e.DiscountSum;
return Convert.ToDecimal(q.Sum());
}
return 0;
}
}
/// <summary>
/// Сумма покупателя
/// </summary>
public decimal BuyerSum { get; set; }
/// <summary>
/// Сдача
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public decimal Change
{
get { return BuyerSum - TotalSum; }
}
/// <summary>
/// Неоплаченный остаток по оплатам в случае смешанной оплаты
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public decimal UnpaidRest
{
get
{
return TotalSum - (from e in Payment
select e.PaymentSum).Sum();
}
}
/// <summary>
/// Сумма всех оплат без конкретной оплаты
/// </summary>
/// <returns></returns>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public decimal SumChargedBonuses
{
get
{
return (from e in ReceiptSpecRecords
select e.ChargedBonuses).Sum();
}
}
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public decimal BonusCardBalanceBeforePayment { get; set; }
/// <summary>
/// Скидка по типам оплаты
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public decimal SumPaymentDiscount
{
get
{
decimal result = 0;
if (Payment.Count > 0)
{
IEnumerable<decimal> q = from p in Payment
where p.PayType.IsDiscount
select p.PaymentSum;
result = q.Sum();
}
return result;
}
}
/// <summary>
/// Необходимо начислить бонусы на чек
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public bool NeedBonusCharge { get; set; }
/// <summary>
/// Код карты покупаетеля
/// </summary>
public string CustomerCardCode { get; set; }
/// <summary>
/// Код системной карты
/// </summary>
public string SystemCardCode { get; set; }
/// <summary>
/// Есть ли в чеке оплата CLM
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public bool HasClmPayment
{
get
{
return
Payment.Any(
t =>
(t.PayType.PayTypeInfo == PayTypeInfo.CLMBonus) ||
(t.PayType.PayTypeInfo == PayTypeInfo.CLMCertificate));
}
}
/// <summary>
/// Пропорция оплаты скидочными и обычными типами оплаты
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
public Double KoeffDiscountPayment
{
get
{
decimal truePaymentSum = 0;
decimal discountPaymentSum = 0;
foreach (Payment p in Payment)
{
if (p.PayType.IsDiscount) discountPaymentSum = discountPaymentSum + p.PaymentSum;
else truePaymentSum = truePaymentSum + p.PaymentSum;
}
double result = 1;
if (discountPaymentSum != 0)
result = 1 - Convert.ToDouble(discountPaymentSum/(discountPaymentSum + truePaymentSum));
return (result);
}
}
/// <summary>
/// Дисконтная карта
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public DiscountCard DiscountCard { get; set; }
/// <summary>
/// Чек возвращеный по чеку основанию
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public bool IsBaseReturned { get; set; }
/// <summary>
/// Есть оплата бнал
/// </summary>
[DBIgnoreReadParam]
[DBIgnoreAutoGenerateParam]
[XmlIgnore]
public bool HasCashPayment
{
get
{
bool res = false;
try
{
res = Payment.Exists(q => q.PayType.IsCashless == false);
}
catch (Exception)
{
// ignored
}
return res;
}
}
/// <summary>
/// Распределение скидки на оплату по позициям чека
/// </summary>
private void ApplyPaymentDiscount()
{
if (SumPaymentDiscount > 0)
{
//На каждую позицию расчитываем скидку
decimal fdiscount = 0;
foreach (ReceiptSpecRecord r in GetRecords())
{
decimal disc = Math.Round(r.PosSum*Convert.ToDecimal(1 - KoeffDiscountPayment), 2);
fdiscount = fdiscount + disc;
r.DiscountSum = r.DiscountSum + disc;
}
//Изза округлений суммы могут быть не равны
if (fdiscount != SumPaymentDiscount)
{
//определяем разницу на наибольшую позицию в чеке
ReceiptSpecRecord r = (from rec in GetRecords()
where rec.PosSum > Math.Abs(SumPaymentDiscount - fdiscount)
orderby rec.PosSum descending
select rec).First();
r.DiscountSum = r.DiscountSum + SumPaymentDiscount - fdiscount;
}
}
}
/// <summary>
/// Удаление позиции
/// </summary>
/// <param name="index"></param>
public void DeletePos(int index)
{
ReceiptSpecRecord r = (from p in ReceiptSpecRecords where p.NumPos == index select p).FirstOrDefault();
if (r != null) r.IsDeleted = true;
}
/// <summary>
/// Получение неудаленных записей
/// </summary>
/// <returns>Не свойством чтобы не было лишних записей в сериализации</returns>
public List<ReceiptSpecRecord> GetRecords()
{
return (from r in ReceiptSpecRecords where (!r.IsDeleted) && (r.Quantity > 0) select r).ToList();
}
/// <summary>
/// Полчение предыдущего неудаленного номера позиции
/// </summary>
/// <returns></returns>
public int GetPrevIndex(int oldNum)
{
List<int> v =
(from r in ReceiptSpecRecords where r.IsDeleted == false && r.NumPos < oldNum select r.NumPos).ToList();
if (v.Count != 0)
return v.Max();
return oldNum;
}
/// <summary>
/// Полчение следующего неудаленного номера позиции
/// </summary>
/// <param name="oldNum"></param>
/// <returns></returns>
public int GetNextIndex(int oldNum)
{
List<int> v =
(from r in ReceiptSpecRecords where r.IsDeleted == false && r.NumPos > oldNum select r.NumPos).ToList();
if (v.Count != 0)
return v.Min();
return oldNum;
}
/// <summary>
/// Добавляем оплату
/// </summary>
/// <param name="payType"></param>
/// <param name="sumToPay"></param>
public void AddPayment(PayType payType, decimal sumToPay)
{
Payment pt = (from p in Payment where p.PayType == payType select p).FirstOrDefault();
if (pt == null)
{
if ((payType.PayTypeInfo == PayTypeInfo.CLMBonus) || (payType.PayTypeInfo == PayTypeInfo.CLMCertificate))
throw new Exception("Для проведения платежа сначала необходимо ввести карту!");
Payment.Add(new Payment
{
PayType = payType,
PaymentSum = sumToPay,
IdPayType = payType.Id,
IdReceipt = Id
});
}
else
{
//Если сумма 0 - удаляем оплату вообще
if (sumToPay == 0)
Payment.Remove(pt);
else
{
decimal summer = 0;
//проходимся по всем картам платежа, меняем сумму оплаты
for (int i = 0; i < pt.CardPayments.Count; i++)
{
if (summer + pt.CardPayments[i].TranSum >= sumToPay)
{
pt.CardPayments[i].TranSum = sumToPay - summer;
//удяляем оставшиеся карты
if (pt.CardPayments.Count > i + 1)
pt.CardPayments.RemoveRange(i + 1, pt.CardPayments.Count - i - 1);
break;
}
summer = summer + pt.CardPayments[i].TranSum;
}
pt.PaymentSum = sumToPay;
}
}
}
/// <summary>
/// Сумма всех оплат без конкретной оплаты
/// </summary>
/// <param name="payType"></param>
/// <returns></returns>
public decimal SumExceptPayment(PayType payType)
{
return (from p in Payment where p.PayType != payType select p.PaymentSum).Sum();
}
/// <summary>
/// Сумма оплаты по типу оплаты
/// </summary>
/// <param name="payType"></param>
/// <returns></returns>
public decimal SumOfPayment(PayType payType)
{
return (from p in Payment where p.PayType == payType select p.PaymentSum).Sum();
}
/// <summary>
/// Изменение количества позиции
/// </summary>
/// <param name="numPos"></param>
/// <param name="quantity"></param>
/// <param name="maxReceiptSum"></param>
public void ChangeQuant(int numPos, decimal quantity, decimal? maxReceiptSum)
{
ReceiptSpecRecord row = (from r in ReceiptSpecRecords where r.NumPos == numPos select r).SingleOrDefault();
if (row != null)
{
if (row.Price*quantity >= maxReceiptSum)
throw new Exception("Сумма чека превышает предельно допустимую сумму");
row.Quantity = (double) quantity;
}
}
/// <summary>
/// Применяем процентную скидку на все позиции
/// </summary>
/// <param name="discount"> процент скидки</param>
/// <param name="discountType"></param>
public void ApplyPercentDiscount(decimal discount, DiscountType discountType)
{
foreach (ReceiptSpecRecord r in GetRecords())
{
if (r.PromoActionEnabled)
{
r.DiscountSum = Math.Round(r.PosSumWoDisc*discount/100, 2);
for (int i = 0; i < r.Discounts.Count; i++)
{
if (r.Discounts[i].DiscountType == discountType)
{
r.Discounts.RemoveAt(i);
i--;
}
}
r.Discounts.Add(new ReceiptDiscount
{
DiscountType = discountType,
DiscountSum = r.DiscountSum,
IdDiscountReason = null,
IdReceipt = Id,
NumPos = r.NumPos,
PercentDiscount = discount
});
}
}
}
/// <summary>
/// Применяем суммовую скидку на все позиции
/// </summary>
/// <param name="discount"> сумма скидки</param>
/// <param name="discountType"></param>
public void ApplySumDiscount(decimal discount, DiscountType discountType)
{
//Пробуем размазать скидку пропорционально на всем позиции
if (discount > TotalSum) discount = TotalSum;
decimal percentDiscount = discount/TotalSum;
decimal fdiscount = 0;
foreach (ReceiptSpecRecord r in GetRecords())
{
if (r.PromoActionEnabled)
{
decimal disc = Math.Round(r.PosSum*percentDiscount, 2);
fdiscount = fdiscount + disc;
r.DiscountSum = r.DiscountSum + disc;
for (int i = 0; i < r.Discounts.Count; i++)
{
if (r.Discounts[i].DiscountType == discountType)
{
r.Discounts.RemoveAt(i);
i--;
}
}
r.Discounts.Add(new ReceiptDiscount
{
DiscountType = discountType,
DiscountSum = r.DiscountSum,
IdDiscountReason = null,
IdReceipt = Id,
NumPos = r.NumPos
});
}
}
//Изза округлений суммы могут быть не равны
if (fdiscount != discount)
{
//определяем разницу на наибольшую позицию в чеке в позициях у которых разрешены скидки
ReceiptSpecRecord r = (from rec in GetRecords()
where (rec.PosSum > Math.Abs(discount - fdiscount)) && (rec.PromoActionEnabled)
orderby rec.PosSum descending
select rec).FirstOrDefault();
if (r == null) throw new Exception("Невозможно рассчитать скидку!");
r.DiscountSum = r.DiscountSum + discount - fdiscount;
for (int i = 0; i < r.Discounts.Count; i++)
{
if (r.Discounts[i].DiscountType == discountType)
{
r.Discounts.RemoveAt(i);
i--;
}
}
r.Discounts.Add(new ReceiptDiscount
{
DiscountType = discountType,
DiscountSum = r.DiscountSum,
IdDiscountReason = null,
IdReceipt = Id,
NumPos = r.NumPos
});
}
}
/// <summary>
/// Применяем скидку на конкретную позицю
/// </summary>
/// <param name="discount"> процент скидки</param>
/// <param name="numPos">номер позиции</param>
/// <param name="idDiscountReason">идентификатор причины ручной скидки</param>
public void ApplyDiscount(decimal discount, int numPos, int? idDiscountReason)
{
ReceiptSpecRecord row = (from r in ReceiptSpecRecords where r.NumPos == numPos select r).SingleOrDefault();
if (row != null)
{
row.DiscountSum = Math.Round(row.PosSumWoDisc*discount/100, 2);
for (int i = 0; i < row.Discounts.Count; i++)
{
if (row.Discounts[i].DiscountType == DiscountType.ManualPosDiscount)
{
row.Discounts.RemoveAt(i);
i--;
}
}
row.Discounts.Add(new ReceiptDiscount
{
DiscountType = DiscountType.ManualPosDiscount,
DiscountSum = row.DiscountSum,
IdDiscountReason = idDiscountReason,
IdReceipt = Id,
NumPos = row.NumPos,
PercentDiscount = discount
});
}
}
/// <summary>
/// Назначение продавца на выбранную позицию
/// </summary>
/// <param name="numPos">номер позиции в чеке</param>
/// <param name="seller">продавец</param>
public void ApplySeller(int numPos, Seller seller)
{
ReceiptSpecRecord r = (from p in ReceiptSpecRecords where p.NumPos == numPos select p).FirstOrDefault();
if (r != null)
{
r.IdSeller = seller.Id;
r.Seller = seller;
}
}
/// <summary>
/// Получение id продавца по номеру позиции в чеке
/// </summary>
/// <param name="currPos"></param>
/// <returns></returns>
public long GetSellerName(int currPos)
{
long? idSeller =
(from r in ReceiptSpecRecords where r.NumPos == currPos select r.IdSeller).SingleOrDefault();
if (idSeller != null) return (long) idSeller;
return 0;
}
/// <summary>
/// Добавление типа оплаты с картой
/// </summary>
/// <param name="payType"></param>
/// <param name="paySum"></param>
/// <param name="cardCode"></param>
public void AddPayment(PayType payType, decimal paySum, string cardCode)
{
Payment pt = (from p in Payment where p.PayType == payType select p).SingleOrDefault();
if (pt == null)
{
var p = new Payment {PayType = payType, PaymentSum = paySum, IdPayType = payType.Id, IdReceipt = Id};
p.CardPayments.Add(new CardPayment
{
CardCode = cardCode,
IdPayType = p.IdPayType,
TranSum = paySum,
IdReceipt = Id
});
Payment.Add(p);
}
else
{
if (!pt.CardPayments.Exists(q => q.CardCode == cardCode))
pt.CardPayments.Add(new CardPayment
{
CardCode = cardCode,
IdPayType = pt.IdPayType,
TranSum = paySum
});
}
}
/// <summary>
/// Меняет идентификатор у всей спецификации и оплаты (в случае удаления чека)
/// </summary>
public void ChangeSpecIds()
{
foreach (ReceiptSpecRecord r in ReceiptSpecRecords)
{
r.IdReceipt = Id;
}
foreach (Payment p in Payment)
{
p.IdReceipt = Id;
}
}
/// <summary>
/// Изменение цены
/// </summary>
/// <param name="numPos"></param>
/// <param name="price"></param>
/// <param name="maxReceiptSum"></param>
public void ChangePrice(int numPos, decimal price, decimal? maxReceiptSum)
{
ReceiptSpecRecord row = (from r in ReceiptSpecRecords where r.NumPos == numPos select r).SingleOrDefault();
if (row != null)
{
if (Convert.ToDecimal(row.Quantity)*price >= maxReceiptSum)
throw new Exception("Сумма чека превышает предельно допустимую сумму");
row.Price = price;
}
}
/// <summary>
/// Убираем скидку у сохраненного чека оплаченой скидочным типом оплаты
/// </summary>
public void ClearPaymentDiscount()
{
if (SumPaymentDiscount > 0)
{
//из каждой позиции удаляем скидку
decimal fdiscount = 0;
foreach (ReceiptSpecRecord r in GetRecords())
{
decimal disc = Math.Round(r.PosSumWoDisc*Convert.ToDecimal(1 - KoeffDiscountPayment), 2);
if (disc > r.DiscountSum) disc = r.DiscountSum;
r.DiscountSum = r.DiscountSum - disc;
fdiscount = fdiscount + disc;
}
//Изза округлений суммы могут быть не равны
if (fdiscount != SumPaymentDiscount)
{
//определяем разницу на наибольшую позицию в чеке
ReceiptSpecRecord r = (from rec in GetRecords()
where rec.DiscountSum >= Math.Abs(SumPaymentDiscount - fdiscount)
orderby rec.PosSum descending
select rec).First();
r.DiscountSum = r.DiscountSum - (SumPaymentDiscount - fdiscount);
}
}
}
/// <summary>
/// Отмена cкидок в чеке кроме ручных
/// </summary>
public void CancelDiscounts()
{
foreach (ReceiptSpecRecord r in ReceiptSpecRecords)
{
//var sumDiscount =
// r.Discounts.Where(
// d =>
// (d.DiscountType == DiscountType.ManualReceiptDiscount) ||
// (d.DiscountType == DiscountType.ManualPosDiscount)).Sum(d => d.DiscountSum);
//r.DiscountSum = sumDiscount;
r.DiscountSum = 0;
}
}
public string GetRrn()
{
string result = "";
List<Payment> v = (from p in Payment where p.RRN != "" select p).ToList();
if (v.Count > 0)
result = v[0].RRN;
return result;
}
}
} |
using System;
namespace HTB.v2.intranetx.bank
{
public partial class Bank : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel.DataAnnotations;
namespace EmployeeTaskMonitor.Core.Models
{
public class EmployeeRequestModel
{
public int Id { get; set; }
[Required]
[StringLength(150)]
public string FirstName { get; set; }
[Required]
[StringLength(150)]
public string LastName { get; set; }
[DataType(DataType.Date)]
public DateTime HiredDate { get; set; }
//1 Employee - many Tasks
public List<TaskResponseModel> Tasks { get; set; }
}
public class TaskRequestModel
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public string TaskName { get; set; }
[DataType(DataType.Date)]
public DateTime StartTime { get; set; }
[DataType(DataType.Date)]
public DateTime Deadline { get; set; }
}
}
|
using System.Collections.Generic;
namespace DataAccesLayer.Repositories
{
public interface IRepository<T> where T : class
{
void New(T entity);
void Save(int index, T entity);
void Delete(int index);
void SaveAllChanges();
List<T> GetAll();
T GetByNamn(string namn);
string GetName(int index);
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace com.Sconit.Entity.MD
{
[Serializable]
public partial class SwitchTrading : EntityBase, IAuditable
{
#region O/R Mapping Properties
public Int32 Id { get; set; }
[Display(Name = "SwitchTrading_Flow", ResourceType = typeof(Resources.MD.SwitchTrading))]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))]
public string Flow { get; set; }
[Display(Name = "SwitchTrading_Supplier", ResourceType = typeof(Resources.MD.SwitchTrading))]
public string Supplier { get; set; }
[Display(Name = "SwitchTrading_Customer", ResourceType = typeof(Resources.MD.SwitchTrading))]
public string Customer { get; set; }
[Display(Name = "SwitchTrading_PurchaseGroup", ResourceType = typeof(Resources.MD.SwitchTrading))]
public string PurchaseGroup { get; set; }
[Display(Name = "FlowMaster_SalesOrg", ResourceType = typeof(Resources.SCM.FlowMaster))]
public string SalesOrg { get; set; }
[Display(Name = "FlowMaster_DistrChan", ResourceType = typeof(Resources.SCM.FlowMaster))]
public string DistrChan { get; set; }
public string DIVISION { get; set; }
public Int32 CreateUserId { get; set; }
[Display(Name = "SwitchTrading_CreateUserName", ResourceType = typeof(Resources.MD.SwitchTrading))]
public string CreateUserName { get; set; }
[Display(Name = "SwitchTrading_CreateDate", ResourceType = typeof(Resources.MD.SwitchTrading))]
public DateTime CreateDate { get; set; }
public Int32 LastModifyUserId { get; set; }
[Display(Name = "SwitchTrading_LastModifyUserName", ResourceType = typeof(Resources.MD.SwitchTrading))]
public string LastModifyUserName { get; set; }
[Display(Name = "SwitchTrading_LastModifyDate", ResourceType = typeof(Resources.MD.SwitchTrading))]
public DateTime LastModifyDate { get; set; }
[Display(Name = "PriceListDetail_PriceList", ResourceType = typeof(Resources.BIL.PriceListDetail))]
public string PriceList { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != null)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
SwitchTrading another = obj as SwitchTrading;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using Spectre.Console;
namespace WitsmlExplorer.Console.Extensions
{
public static class StringExtensions
{
public static string WithColor(this string text, Color color) => $"[{color}]{text}[/]";
public static string Bold(this string text) => $"[bold]{text}[/]";
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LimenawebApp.Models.Frezzers
{
public class GetFrezzers_api
{
public int? code { get; set; }
public string message { get; set; }
public List<Frezzers_api> data { get; set; }
}
public class GetFrezzer_api
{
public int? code { get; set; }
public string message { get; set; }
public Frezzers_api data { get; set; }
}
public class Frezzers_api
{
public string code { get; set; }
public string name { get; set; }
public string whs { get; set; }
public string active { get; set; }
}
public class Mdl_Frezzers
{
}
} |
using YourContacts.Contracts;
using YourContacts.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace YourContacts.Services.Database.Sql.Translators
{
public class ModelToSqlEntityTranslator : ITranslator<Contact, ContactDetail>
{
public ContactDetail Translate(Contact request)
{
ContactDetail contactDetail = null;
if (request != null)
{
contactDetail = new ContactDetail
{
ID = request.ID,
FirstName = request?.FirstName == null ? "" : request.FirstName,
LastName = request?.LastName == null ? "" : request.LastName,
Email = request?.Email == null ? "" : request.Email,
PhoneNumber = request?.PhoneNumber == null ? "" : request.PhoneNumber,
Status = GetStatus(request.Status)
};
}
return contactDetail;
}
private int? GetStatus(Status status)
{
switch (status)
{
case Status.Undefined:
return null;
case Status.Inactive:
return 0;
case Status.Active:
return 1;
default:
return null;
}
}
}
} |
using MyOnlineShop.DataAccess.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace MyOnlineShop.DataAccess.ViewModels
{
public class CustomerViewModel
{
public IEnumerable<Customer> Customers { get; set; }
public Customer Customer { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace BadSmellsTest.ExtractMethod
{
class Pedido
{
public int ObterValor()
{
return 1;
}
}
class Antes
{
public readonly string Nome;
private readonly List<Pedido> _pedidos;
public Antes(string nome, List<Pedido> pedidos)
{
Nome = nome;
_pedidos = pedidos;
}
}
class Depois
{
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class EventsBehaviour : MonoBehaviour
{
public UnityEvent mouseDownEvent;
public UnityEvent onTriggerEvent;
public UnityEvent exitTriggerEvent;
public void OnMouseDown()
{
mouseDownEvent.Invoke();
}
public void OnTriggerEnter(Collider other)
{
onTriggerEvent.Invoke();
}
public void OnTriggerExit(Collider other)
{
exitTriggerEvent.Invoke();
}
}
|
using Anywhere2Go.Business.Master;
using Anywhere2Go.DataAccess.Object;
using Anywhere2Go.Library.Datatables;
using Claimdi.Web.TH.Filters;
using Claimdi.Web.TH.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Claimdi.Web.TH.Controllers
{
public class MapTrackingController : Controller
{
// GET: MapTracking
[AuthorizeUser(AccessLevel = "View", PageAction = "MapTracking")]
public ActionResult Index(AccidentLocationSearch model)
{
if (string.IsNullOrEmpty(model.StartDate) && string.IsNullOrEmpty(model.EndDate))
{
model.StartDate = DateTime.Now.ToString("dd/MM/yyyy");
model.EndDate = DateTime.Now.ToString("dd/MM/yyyy");
}
if (string.IsNullOrEmpty(model.StartTime) && string.IsNullOrEmpty(model.EndTime))
{
model.StartTime = DateTime.Now.Hour.ToString() + ":00";
model.EndTime = DateTime.Now.AddHours(1).Hour.ToString () +":00";
}
var func = new MappingAPILogic();
var result = func.GetAccidentLocation(model);
if (result != null)
{
model.AccidentLocation = result;
}
ViewBag.HoursList = getHours();
return View(model);
}
[AuthorizeUser(AccessLevel = "View", PageAction = "MapTracking")]
public ActionResult MapTrackingInsurer()
{
return View();
}
public List<SelectListItem> getHours()
{
List<SelectListItem> ls = new List<SelectListItem>();
ls.Add(new SelectListItem() { Text = "0:00", Value = "0:00" });
ls.Add(new SelectListItem() { Text = "1:00", Value = "1:00" });
ls.Add(new SelectListItem() { Text = "2:00", Value = "2:00" });
ls.Add(new SelectListItem() { Text = "3:00", Value = "3:00" });
ls.Add(new SelectListItem() { Text = "4:00", Value = "4:00" });
ls.Add(new SelectListItem() { Text = "5:00", Value = "5:00" });
ls.Add(new SelectListItem() { Text = "6:00", Value = "6:00" });
ls.Add(new SelectListItem() { Text = "7:00", Value = "7:00" });
ls.Add(new SelectListItem() { Text = "8:00", Value = "8:00" });
ls.Add(new SelectListItem() { Text = "9:00", Value = "9:00" });
ls.Add(new SelectListItem() { Text = "10:00", Value = "10:00" });
ls.Add(new SelectListItem() { Text = "11:00", Value = "11:00" });
ls.Add(new SelectListItem() { Text = "12:00", Value = "12:00" });
ls.Add(new SelectListItem() { Text = "13:00", Value = "13:00" });
ls.Add(new SelectListItem() { Text = "14:00", Value = "14:00" });
ls.Add(new SelectListItem() { Text = "15:00", Value = "15:00" });
ls.Add(new SelectListItem() { Text = "16:00", Value = "16:00" });
ls.Add(new SelectListItem() { Text = "17:00", Value = "17:00" });
ls.Add(new SelectListItem() { Text = "18:00", Value = "18:00" });
ls.Add(new SelectListItem() { Text = "19:00", Value = "19:00" });
ls.Add(new SelectListItem() { Text = "20:00", Value = "20:00" });
ls.Add(new SelectListItem() { Text = "21:00", Value = "21:00" });
ls.Add(new SelectListItem() { Text = "22:00", Value = "22:00" });
ls.Add(new SelectListItem() { Text = "23:00", Value = "23:00" });
return ls;
}
public List<SelectListItem> GetDropDownSuperBikeDepartment(Guid ComId)
{
DepartmentLogic obj = new DepartmentLogic();
List<SelectListItem> ls = new List<SelectListItem>();
var department = obj.getSuperBikeDepartmentList(ComId).OrderBy(t=>t.deptName);
ls.Add(new SelectListItem() { Text = "แผนก", Value = "" });
foreach (var temp in department)
{
ls.Add(new SelectListItem() { Text = temp.deptName, Value = temp.deptId });
}
return ls;
}
[AuthorizeUser(AccessLevel = "View", PageAction = "Surveyor")]
public ActionResult SurveyorTracking()
{
var auth = ClaimdiSessionFacade.ClaimdiSession;
TaskLogic task = new TaskLogic();
ViewBag.SuperBikeBranch = this.GetDropDownSuperBikeDepartment(auth.com_id);
return View();
}
[HttpPost]
public JsonResult AjaxGetSurveyorOnlineTrackingHandler(DTParameters param)
{
try
{
var auth = ClaimdiSessionFacade.ClaimdiSession;
MapTrackingLogic tracking = new MapTrackingLogic();
DTResultSurveyorOnlineTracking<MapTrackingResultModel> result = tracking.GetSurveyorOnlineTrackingList(param, auth);
return Json(result);
}
catch (Exception ex)
{
return Json(new { error = ex.Message });
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWorkFlow.DataBase;
namespace IWorkFlow.ORM
{
[Serializable]
[DataTableInfo("B_OA_FileList", "id")]
public class B_OA_FileList : QueryInfo
{
#region Model
/// <summary>
/// id
/// </summary>
///
[DataField("id", "B_OA_FileList",false)]
public int id
{
set { _id = value; }
get { return _id; }
}
private int _id;
/// <summary>
/// 新闻ID
/// </summary>
///
[DataField("NewsId", "B_OA_FileList")]
public string NewsId
{
set { _NewsId = value; }
get { return _NewsId; }
}
private string _NewsId;
/// <summary>
/// 文件名
/// </summary>
///
[DataField("FileName", "B_OA_FileList")]
public string FileName
{
set { _FileName = value; }
get { return _FileName; }
}
private string _FileName;
/// <summary>
/// 文件相对路径
/// </summary>
///
[DataField("RelativePath", "B_OA_FileList")]
public string RelativePath
{
set { _RelativePath = value; }
get { return _RelativePath; }
}
private string _RelativePath;
/// <summary>
/// 文件绝对路径
/// </summary>
///
[DataField("AbsolutePath", "B_OA_FileList")]
public string AbsolutePath
{
set { _AbsolutePath = value; }
get { return _AbsolutePath; }
}
private string _AbsolutePath;
/// <summary>
/// 扩展名
/// </summary>
///
[DataField("Extension", "B_OA_FileList")]
public string Extension
{
set { _Extension = value; }
get { return _Extension; }
}
private string _Extension;
/// <summary>
///文件大小(KB)
/// </summary>
///
[DataField("FileSize", "B_OA_FileList")]
public int FileSize
{
set { _FileSize = value; }
get { return _FileSize; }
}
private int _FileSize;
/// <summary>
/// 上传前文件名
/// </summary>
///
[DataField("BeforeFileName", "B_OA_FileList")]
public string BeforeFileName
{
set { _BeforeFileName = value; }
get { return _BeforeFileName; }
}
private string _BeforeFileName;
/// <summary>
/// 部门
/// </summary>
///
[DataField("Dept", "B_OA_FileList")]
public string Dept
{
set { _Dept = value; }
get { return _Dept; }
}
private string _Dept;
#endregion Model
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace TumblrDownloader
{
class ResourcesDownloader
{
//private TumblrResource[] ToDownRes = null;
private List<TumblrResource> ToDownRes = null;
private TDownProxy tumDownProxy = null;
private bool SaveResourcesToFolderWithPostName = false;
private string TumblrResourceSize ="";
private HttpWebRequest TumDownReq = null;
private HttpWebResponse TumDownRes = null;
private Stream tumStream = null;
public event EventHandler<TumblrEventArgs> OnOneResourceDownloaded;
private DBOperator dbo = null;
private void CallOneResourceDownloadedEvent(TumblrEventArgs e)
{
if (OnOneResourceDownloaded != null)
{
OnOneResourceDownloaded.Invoke(this, e);
}
}
public ResourcesDownloader()
{
}
public ResourcesDownloader(String pAddr, String port, Int32 tOut)
{
tumDownProxy = new TDownProxy(pAddr, port, tOut);
DirectoryInfo tumDI = new DirectoryInfo(Program.TumblrResourcesFolder);
dbo = new DBOperator();
if (!tumDI.Exists)
{
tumDI.Create();
}
}
public void StartDownLoad()
{
Console.WriteLine(System.Threading.Thread.CurrentThread.Name+"线程待下载资源数量是:" + ToDownRes.Count);
if (ToDownRes.Count<TumblrResource>() > 0)
{
foreach (TumblrResource tr in ToDownRes)
{
String tumResFilePath = Program.TumblrResourcesFolder + tr.ResourceName;
FileInfo tumResFileInfo = new FileInfo(tumResFilePath);
long tumContentLength = 0;
if (!tumResFileInfo.Exists)
{
if (true)
{
try
{
TumDownReq = tumDownProxy.GetHttpWebRequest(tr.ResourceURL);
TumDownRes = (HttpWebResponse)TumDownReq.GetResponse();
byte[] imageBuffer = new byte[Program.TumblrResourceBufferSize];
if (TumDownRes.StatusCode == HttpStatusCode.OK)
{
tumStream = TumDownRes.GetResponseStream();
tumContentLength = TumDownRes.ContentLength;
int tumResSize_KB = (int)Math.Round((double)tumContentLength / 1024, 0);
double tumResSize_MB = Math.Round((double)tumContentLength / 1024 / 1024, 2);
if (tumResSize_KB < 10240)
{
TumblrResourceSize = tumResSize_KB + " KB";
}
else
{
TumblrResourceSize = tumResSize_MB + " MB";
}
Console.WriteLine("编号为"+tr.ResourceIndex +"资源长度: " + TumblrResourceSize);
int readSize = tumStream.Read(imageBuffer, 0, imageBuffer.Length);
int filelenth = 0;
FileStream tumFS = new FileStream(tumResFilePath, FileMode.Create);
while (readSize > 0)
{
tumFS.Write(imageBuffer, 0, readSize);
filelenth = filelenth + readSize;
readSize = tumStream.Read(imageBuffer, 0, imageBuffer.Length);
Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "已写入长度: " + tumFS.Length);
}
tumFS.Close();
tumStream.Close();
TumblrEventArgs tea = new TumblrEventArgs();
dbo.UpdateTumblrResourceItem(tr.ResourceIndex, tumContentLength.ToString(), DateTime.Now.ToString());
tea.TumblrResourceDownloadStatus = "DN";
tea.TumblrResourceIndex = tr.ResourceIndex;
tea.TumblrResourceSize = this.TumblrResourceSize;
tea.TumblrResourceTime = DateTime.Now.ToString();
CallOneResourceDownloadedEvent(tea);
}
}
catch (IOException e)
{
Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "下载:"+ tr.ResourceIndex + ",发生IO异常:" + e.Message);
}
catch (WebException e)
{
Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "下载:" + tr.ResourceIndex + ",发生NET异常:" + e.Message);
}
finally
{
if (TumDownRes != null)
{
TumDownRes.Close();
}
if (TumDownReq != null)
{
TumDownReq.Abort();
}
}
}
/*
else if (tr.ResourceType == "video")
{
}
*/
}
else
{
//文件已存在
}
}
}
}
public void SetDownloadResources(List<TumblrResource> tdr)
{
ToDownRes = tdr;
}
}
}
|
using CarBooking.API.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Reflection;
namespace CarBooking.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CarBookingDataContext>(options => options.UseSqlServer(
Configuration["ConnectionStrings:DefaultConnection"]));
services.AddControllers().AddNewtonsoftJson(settings =>
settings.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//// Source: https://stackoverflow.com/questions/41090881/migrating-at-runtime-with-entity-framework-core
using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
// FIXME: Database connection can sometimes not be established.
scope.ServiceProvider.GetService<CarBookingDataContext>().Database.Migrate();
// Load and execute the import script
var assembly = typeof(Startup).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("CarBooking.API.Import.sql");
StreamReader reader = new StreamReader(stream);
string importScript = reader.ReadToEnd();
scope.ServiceProvider.GetService<CarBookingDataContext>().Database.ExecuteSqlRaw(importScript);
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
public static bool CanConnect(CarBookingDataContext service)
{
try
{
return service.Database.CanConnect();
}
catch (Exception)
{
return false;
}
}
}
}
|
using System;
using System.IO;
using System.Linq;
namespace Graphs.FileUtilities
{
internal class ReportGenerator : FileGraphReader
{
public ReportGenerator()
{
ReportPath = DirectoryPath + @"\\Reports\\";
}
private string ReportPath { get; set; }
public void GenerateStandardRaport(StandardTestReport testRaport)
{
var fileName = String.Format("Standard_report_{0}.txt", GetTimestamp());
using (var file = new StreamWriter(ReportPath + fileName))
{
file.WriteLine("Standard test raport");
file.WriteLine(new string('-', 50));
file.WriteLine("Generation time: {0}", GetTimestamp("u"));
WriteStandardTestReport(file, testRaport);
}
}
private void WriteStandardTestReport(StreamWriter file, StandardTestReport report)
{
file.WriteLine("Algorithm:" + report.AlgorithmName);
file.WriteLine("=== Pass: {0} ===", (report.DidPass ? "true" : "false"));
file.WriteLine("Execution time: " + report.PerformanceReport.ExecutionTime);
file.WriteLine("Number of nodes: " + report.NodeNum);
file.WriteLine("From node: " + report.FromNode);
file.WriteLine("To node: " + report.ToNode);
}
public void GeneratePerformanceReport(PerformanceTestReport report)
{
var fileName = String.Format("Performance_report_{0}.txt", GetTimestamp());
using (var file = new StreamWriter(ReportPath + fileName))
{
file.WriteLine("Performance test report");
file.WriteLine(new string('-', 50));
file.WriteLine("Generation time: {0}", GetTimestamp("u"));
WritePerformanceTestReport(file, report);
}
}
private static void WritePerformanceTestReport(TextWriter file, PerformanceTestReport report)
{
var doubleSeparator = new string('=', 50);
var maxCpu = report.MostCpuConsumingTest;
var minCpu = report.LeastCpuConsumingTest;
var maxRam = report.MostRamConsumingTest;
var minRam = report.LeastRamConsumingTest;
var testsCount = report.PerformanceReports.Count();
file.WriteLine("Algorithm: {0}", report.AlgorithmName);
file.WriteLine("Tests count: {0}", testsCount);
file.WriteLine("\n" + doubleSeparator);
file.WriteLine("Summary:");
file.WriteLine(doubleSeparator);
file.WriteLine("Highest Cpu usage: {0}% - test {1}/{2}", maxCpu.Value, maxCpu.Index + 1, testsCount);
file.WriteLine("Smallest Cpu usage: {0}% - test {1}/{2}", minCpu.Value, minCpu.Index + 1, testsCount);
file.WriteLine("Highest RAM usage: {0}MB - test {1}/{2}", maxRam.Value, maxRam.Index + 1, testsCount);
file.WriteLine("Smallest RAM usage: {0}MB - test {1}/{2}", minRam.Value, minRam.Index + 1, testsCount);
file.WriteLine("\n" + doubleSeparator);
file.WriteLine("Detailed information about every test");
file.WriteLine(doubleSeparator);
for (var i = 0; i < report.NodeNums.Length; i++)
{
var perfReport = report.PerformanceReports[i];
file.WriteLine("Test {0}, has {1} nodes", i + 1, report.NodeNums[i]);
file.WriteLine("\t Took: {0}", perfReport.ExecutionTime.ToString("g"));
file.WriteLine("\t Average CPU usage: {0}%", perfReport.AverageCpuUsage);
file.WriteLine("\t Peak CPU usage: {0}%", perfReport.PeakCpuUsage);
file.WriteLine("\t Average RAM usage: {0}MB", perfReport.AverageRamUsage);
file.WriteLine("\t Peak RAM usage: {0}MB\n", perfReport.PeakRamUsage);
}
file.WriteLine(doubleSeparator);
}
private string GetTimestamp(string format = "yyyy_dd_MM_HH_mm_ss")
{
return DateTime.Now.ToString(format);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveHandler : MonoBehaviour
{
public void SaveToFile()
{
EditorRoomManager.instance.SerializeRoom ();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Volo.Abp.Application.Dtos;
namespace TestAbp
{
public class PeopleDto: EntityDto<int>
{
public virtual int Age { get; set; }
public virtual string Name { get; set; }
}
}
|
namespace Funding.Common.Constants
{
public class Roles
{
public const string Admin = "Admin";
public const string ProjectAdmin = "Project Admin";
}
} |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace lastfmRecommedizer.WebServer
{
class ResponseThread
{
public ResponseThread(HttpListenerContext ListenerContext)
{
HttpListenerResponse Response = ListenerContext.Response;
string rowUrl = ListenerContext.Request.RawUrl;
String ResponseString = "";
if (rowUrl.IndexOf("/user") > -1)
{
string username = ListenerContext.Request.QueryString["name"];
ResponseString = UserPage.getPage(username);
}
else
ResponseString = MainPage.getPage();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(ResponseString);
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.OutputStream.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Repositories.Interfaces;
using Auction = Models.DataModels.Auction;
namespace Tests.MockClasses
{
public class MockAuctionRepo : IAuctionRepo
{
public Task<bool> CreateAuction(Models.DataModels.Auction dim)
{
return Task.FromResult(true);
}
public Task<bool> DeleteAuction(int auctionId)
{
return Task.FromResult(true);
}
public Task<bool> UpdateAuction(Models.DataModels.Auction dim)
{
return Task.FromResult(true);
}
public Task<Models.DataModels.Auction> GetAuction(int auctionId)
{
var auction = new Models.DataModels.Auction
{
AuktionId = 1,
Titel = "Titel",
Beskrivning = "Beskrivning",
StartDatum = new DateTime(2018, 01, 01, 10, 10, 10),
SlutDatum = new DateTime(2040, 02, 01, 10, 10, 10),
Utropspris = 1,
SkapadAv = "Me",
Gruppkod = 1
};
return Task.FromResult(auction);
}
public Task<IList<Models.DataModels.Auction>> GetAuctions()
{
IList<Models.DataModels.Auction> auctions = new List<Models.DataModels.Auction>();
auctions.Add(new Models.DataModels.Auction
{
AuktionId = 1,
Titel = "Titel",
Beskrivning = "Beskrivning",
StartDatum = new DateTime(2018, 01, 01, 10, 10, 10),
SlutDatum = new DateTime(2040, 02, 01, 10, 10, 10),
Utropspris = 1,
SkapadAv = "Me",
Gruppkod = 1
});
auctions.Add(new Models.DataModels.Auction
{
AuktionId = 2,
Titel = "Titel",
Beskrivning = "Beskrivning",
StartDatum = new DateTime(2018, 01, 01, 10, 10, 10),
SlutDatum = new DateTime(2018, 02, 01, 10, 10, 10),
Utropspris = 1,
SkapadAv = "You",
Gruppkod = 1
});
return Task.FromResult(auctions);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Data;
using Property;
using Property_cls;
namespace Property.Admin
{
public partial class Agents : System.Web.UI.Page
{
#region Global
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
cls_Property clsobj = new cls_Property();
#endregion Global
#region Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (Session["FirstName"] != null)
{
if (!IsPostBack)
{
//GetSiteData();
}
}
else
{
Response.Redirect("~/Admin/AdminLogin.aspx", false);
}
}
#endregion Page Load
#region GetSiteData Method
protected void GetSiteData()
{
try
{
DataTable dt = new DataTable();
dt = clsobj.GetAgents();
if (dt.Rows.Count > 0)
{
txtFirstname.Text = Convert.ToString(dt.Rows[0]["FirstName"]);
txtLastName.Text = Convert.ToString(dt.Rows[0]["LastName"]);
txtEamil.Text = Convert.ToString(dt.Rows[0]["Eamil"]);
txtAddress.Text = Convert.ToString(dt.Rows[0]["Address"]);
txtCity.Text = Convert.ToString(dt.Rows[0]["City"]);
txtState.Text = Convert.ToString(dt.Rows[0]["State"]);
txtPhoneNumber.Text = Convert.ToString(dt.Rows[0]["PhoneNumber"]);
txtfax.Text = Convert.ToString(dt.Rows[0]["Fax"]);
txtSiteUrl.Text = Convert.ToString(dt.Rows[0]["SiteUrl"]);
txtcompany.Text = Convert.ToString(dt.Rows[0]["Company"]);
txtpostal.Text = Convert.ToString(dt.Rows[0]["Company"]);
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion GetSiteData Method
#region Button Click
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
{
string fname = System.IO.Path.GetFileName(updBannerImage.FileName);
updBannerImage.SaveAs(Server.MapPath("UploadFiles") + "\\" + System.IO.Path.GetFileName(updBannerImage.FileName));
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "ups_AddAgents";
cmd.Connection = conn;
cmd.Parameters.AddWithValue("@FirstName", txtFirstname.Text);
cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("@Email", txtEamil.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@City", txtCity.Text);
cmd.Parameters.AddWithValue("@State", txtState.Text);
cmd.Parameters.AddWithValue("@PhoneNumber", txtPhoneNumber.Text);
cmd.Parameters.AddWithValue("@Fax", txtfax.Text);
cmd.Parameters.AddWithValue("@SiteUrl", txtSiteUrl.Text);
cmd.Parameters.AddWithValue("@FileName", fname);
cmd.Parameters.AddWithValue("@Company", txtcompany.Text);
cmd.Parameters.AddWithValue("@Country", txtCountry.Text);
cmd.Parameters.AddWithValue("@PostalCode",txtpostal.Text) ;
cmd.Parameters.AddWithValue("@About", txtAbout.Text);
cmd.Parameters.AddWithValue("@Language", ddlLanguage.SelectedItem.Text);
cmd.Parameters.AddWithValue("@Designation", txtDesignation.Text);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
cmd.ExecuteNonQuery();
conn.Close();
clear();
Response.Redirect("~/Admin/ShowAgents.aspx", false);
}
}
catch (Exception ex)
{
//throw ex;
}
}
protected void btnBack_Click(object sender, EventArgs e)
{
Response.Redirect("AdminDashBoard.aspx");
}
public void clear()
{
txtFirstname.Text = string.Empty;
txtLastName.Text = string.Empty;
txtEamil.Text = string.Empty;
txtfax.Text = string.Empty;
txtPhoneNumber.Text = string.Empty;
txtSiteUrl.Text = string.Empty;
txtState.Text = string.Empty;
txtCity.Text = string.Empty;
txtAddress.Text = string.Empty;
txtcompany.Text = string.Empty;
}
#endregion Button Click
}
} |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[RequireComponent(typeof(Rigidbody))]
public class Area : MonoBehaviour
{
[SerializeField] private string areaName;
private List<Collider> areaColliders = new List<Collider> ();
[SerializeField] private Color debugGizmosColour = new Color ( 1.0f, 1.0f, 1.0f, 0.5f );
public string AreaName { get => areaName; }
private void OnTriggerEnter (Collider other)
{
AreaCollider area = other.GetComponent<AreaCollider> ();
if (area == null) return;
if(area.currentArea == null || area.currentArea != this)
{
area.ChangeArea ( this );
}
}
private void OnValidate ()
{
areaColliders = GetComponentsInChildren<Collider> ().ToList ();
}
#if UNITY_EDITOR
private void OnDrawGizmos ()
{
Bounds bounds = new Bounds ();
if(areaColliders.Count > 0)
{
bounds.center = areaColliders[0].bounds.center + new Vector3(0.0f, 10.0f, 0.0f);
bounds.size = areaColliders[0].bounds.size;
}
for (int i = 0; i < areaColliders.Count; i++)
{
Gizmos.color = debugGizmosColour;
Gizmos.DrawCube ( areaColliders[i].bounds.center, areaColliders[i].bounds.size );
}
var centeredStyle = new GUIStyle ( GUI.skin.GetStyle ( "Label" ) );
centeredStyle.alignment = TextAnchor.UpperCenter;
centeredStyle.fontSize = 18;
Handles.Label ( bounds.center, AreaName, centeredStyle );
}
#endif
}
|
using System;
namespace Atomic
{
/// <summary>
/// DES对称算法接口
/// </summary>
public interface IDesSymmetricAlgorithm : IEncryptAlgorithm, IDecryptAlgorithm
{
/// <summary>
/// 获取算法KEY(会自动从conf文件中读取symmetryKey节点配置,或不存在则会启用默认值)
/// </summary>
string AlgorithmKey { get; }
/// <summary>
/// 是否是标准的DES密文格式
/// </summary>
/// <param name="ciphertext">密文</param>
/// <returns></returns>
bool IsCiphertext(string ciphertext);
}
}
|
using System;
using System.Windows;
using System.Windows.Controls;
namespace Ex2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public string FullEquation { get; set; }
bool dotAvailable = false;
bool isFirstNumber = true;
bool newNumber = true;
public MainWindow()
{
InitializeComponent();
resultNumberTextBox.Text = String.Empty;
equationTextBox.Text = String.Empty;
}
private void NumericButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (!String.IsNullOrEmpty(equationTextBox.Text))
{
if (newNumber)
{
// MessageBox.Show("if");
equationTextBox.Text += b.Content;
newNumber = false;
}
else if (equationTextBox.Text.Length >= 2 && equationTextBox.Text[equationTextBox.Text.Length - 2] != '0')
{
//MessageBox.Show("else if");
equationTextBox.Text += b.Content;
}
else if (equationTextBox.Text[equationTextBox.Text.Length - 1] != '0')
equationTextBox.Text += b.Content;
if (isFirstNumber)
{
isFirstNumber = false;
dotAvailable = true;
}
}
else
{
equationTextBox.Text += b.Content;
newNumber = false;
}
}
private void SignButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (String.IsNullOrEmpty(equationTextBox.Text)) return;
char sign = equationTextBox.Text[equationTextBox.Text.Length - 1];
if (sign != '+' && sign != '-' && sign != 'x' && sign != '/' && sign != '.')
equationTextBox.Text += b.Content;
dotAvailable = true;
newNumber = true;
}
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (String.IsNullOrEmpty(equationTextBox.Text)) return;
if (b.Name == "CE")
{
resultNumberTextBox.Text = String.Empty;
}
else if (b.Name == "C")
{
resultNumberTextBox.Text = String.Empty;
equationTextBox.Text = String.Empty;
isFirstNumber = true;
newNumber = true;
}
else if (b.Name == "deleteButton")
{
int equationLength = equationTextBox.Text.Length;
char lastChar = 'n';
char prevToLastChar = 'n';
if (equationLength >= 1)
lastChar = equationTextBox.Text[equationTextBox.Text.Length - 1]; // char to delete
if (equationLength >= 2)
prevToLastChar = equationTextBox.Text[equationTextBox.Text.Length - 2];
if (lastChar == '.')
{
dotAvailable = true;
if (prevToLastChar == '0')
newNumber = false;
}
else if (prevToLastChar == '+' || prevToLastChar == '-' || prevToLastChar == 'x' || prevToLastChar == '/')
{
newNumber = true;
}
equationTextBox.Text = equationTextBox.Text.Remove(equationTextBox.Text.Length - 1, 1);
if (String.IsNullOrEmpty(equationTextBox.Text))
{
newNumber = true;
isFirstNumber = true;
}
}
}
private void EqualsButton_Click(object sender, RoutedEventArgs e)
{
string eq = equationTextBox.Text;
if (eq[eq.Length - 1] == '+' || eq[eq.Length - 1] == '/' || eq[eq.Length - 1] == 'x' || eq[eq.Length - 1] == '-')
return;
if (String.IsNullOrEmpty(eq)) return;
if (!String.IsNullOrEmpty(eq))
{
Double res = 0;
try
{
string prevNumStr = "";
string currNumStr = "";
double prevNum;
double currNum;
String sign = String.Empty;
bool first = true;
for (int i = 0; i < eq.Length; i++)
{
if (eq[i] == '+' || eq[i] == '-' || eq[i] == 'x' || eq[i] == '/') // takes sign
{
if (sign != String.Empty)
{
if (sign == "+")
res += Double.Parse(currNumStr);
else if (sign == "-")
res -= Double.Parse(currNumStr);
else if (sign == "x")
res *= Double.Parse(currNumStr);
else if (sign == "/")
res /= Double.Parse(currNumStr);
//MessageBox.Show($"Res: {res} sign: {sign}");
currNumStr = String.Empty;
}
sign = eq[i].ToString();
if (first)
{
first = false;
res = Double.Parse(currNumStr);
currNumStr = String.Empty;
//MessageBox.Show($"first res: {res}");
}
}
else // takes number
{
currNumStr += eq[i];
}
}
if (sign != String.Empty)
{
if (sign == "+")
res += Double.Parse(currNumStr);
else if (sign == "-")
res -= Double.Parse(currNumStr);
else if (sign == "x")
res *= Double.Parse(currNumStr);
else if (sign == "/")
res /= Double.Parse(currNumStr);
}
}
catch (Exception ex)
{
MessageBox.Show($"Message: {ex.Message}\n\nStack Trace: {ex.StackTrace}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
resultNumberTextBox.Text = res.ToString();
}
}
private void DotButton_Click(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(equationTextBox.Text)) return;
char c = equationTextBox.Text[equationTextBox.Text.Length - 1]; // previoues to dot character
if ((c == '0' || c == '1' || c == '2' || c == '3' ||
c == '4' || c == '5' || c == '6' ||
c == '7' || c == '8' || c == '9') && dotAvailable)
{
equationTextBox.Text += ".";
dotAvailable = false;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace DailyBlogger.Models
{
public class BlogPost
{
[Key]
public int blog_id { get; set; }
public string blog_title { get; set; }
public string content { get; set; }
public DateTime blog_date { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations;
namespace ClipModels
{
public class TrafficList
{
[Key]
public int ID { get; set; }
public virtual TrafficClip TrafficClip { get; set; }
public int TrafficClipId { get; set; }
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MTProto.Client.Core
{
public class TLConstructor
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("predicate")]
public string Predicate { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
public override string ToString()
{
return string.Format("{0}#{1} = {2}", Id, Predicate, Type);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using BattleShots.Droid;
[assembly: Dependency(typeof(ToastLoader))]
namespace BattleShots.Droid
{
public class ToastLoader:IToastInterface
{
public void Show(string message)
{
Toast.MakeText(Android.App.Application.Context, message, ToastLength.Short).Show();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSSCriterias.Logic
{
public interface IReport
{
void Create();
void Open();
}
public abstract class Report : IReport
{
protected IStatGame Game { get; set; }
protected DateTime Creation { get; set; }
public Report(IStatGame game)
{
Game = game;
}
public abstract void Create();
public abstract void Open();
public enum ReportType { Word, PDF, HTML, Excel }
public static IReport GetReport(IStatGame game, ReportType type)
{
Report report;
switch (type)
{
case ReportType.Word:
report = new ReportWord(game);
break;
case ReportType.PDF:
report = new ReportPDF(game);
break;
case ReportType.HTML:
report = new ReportHTML(game);
break;
case ReportType.Excel:
report = new ReportExcel(game);
break;
default:
throw new Exception($"Отчет типа {type} не распознан");
}
return report;
}
}
}
|
using Microsoft.Practices.Unity;
namespace OrgMan.Dependencies
{
public interface IDependencyRegistration
{
void Load(IUnityContainer unityContainer);
}
}
|
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Picture : IDraw
{
public List<Shape> Geometry;
public int NumberOfShapes { get { return Geometry.Count; } set { } }
//my indexer
public Shape[] shapes;
public Shape this[int index]
{
get
{
return shapes[index];
}
set
{
shapes[index] = value;
}
}
public Picture()
{
Geometry = new List<Shape>();
}
public Picture(int collectionLength)
{
Geometry = new List<Shape>(collectionLength);
NumberOfShapes = collectionLength;
}
//methods
//add a new shape method
public void Add(Shape figure)
{
Geometry.Add(figure);
}
//remove by name
public void RemoveByName(string nameToRemove)
{
if (NumberOfShapes == 0)
{
Console.WriteLine("There are nothing to remove - list is empty!");
}
else
{
for (int i = 0; i < NumberOfShapes; i++)
{
if (Geometry[i].Name == nameToRemove)
{
Geometry.Remove(Geometry[i]);
}
}
}
}
//remove by area limitation
public void RemoveByArea(double areaLimit)
{
if (NumberOfShapes == 0)
{
Console.WriteLine("There are nothing to remove - list is empty!");
}
else
{
for (int i = 0; i < NumberOfShapes; i++)
{
if (Geometry[i].Square() > areaLimit)
{
Geometry.Remove(Geometry[i]);
}
}
}
}
//remove by type
public void RemoveByType(Type figure)
{
if (NumberOfShapes == 0)
{
Console.WriteLine("There are nothing to remove - list is empty!");
}
else
{
for (int i = 0; i < NumberOfShapes; i++)
{
if (Geometry[i].GetType() == figure)
{
Geometry.Remove(Geometry[i]);
}
}
}
}
//interface method realisation
public void Draw()
{
if (NumberOfShapes == 0)
{
Console.WriteLine("~The list is empty!~");
}
else
{
int i = 1;
foreach (Shape el in Geometry)
{
Circle c;
Quadrate q;
Triangle t;
if (el is Circle)
{
c = (Circle)el;
Console.WriteLine("Figure # {0}", i++);
c.Draw();
}
else if (el is Quadrate)
{
q = (Quadrate)el;
Console.WriteLine("Figure # {0}", i++);
q.Draw();
}
else
{
t = (Triangle)el;
Console.WriteLine("Figure # {0}", i++);
t.Draw();
}
}
}
}
}
}
|
using Alabo.Exceptions;
using Alabo.Validations;
using System.Linq;
using System.Runtime.Serialization;
namespace Alabo.Domains.Dtos {
/// <summary>
/// 请求参数
/// </summary>
[DataContract]
public abstract class RequestBase : IRequest {
/// <summary>
/// 验证
/// </summary>
public virtual ValidationResultCollection Validate() {
var result = DataAnnotationValidation.Validate(this);
if (result.IsValid) {
return ValidationResultCollection.Success;
}
throw new ValidException(result.First().ErrorMessage);
}
}
} |
using System;
namespace Axon
{
public class Material
{
public Texture Texture;
public Shader Shader;
public Material(Shader Shader, String TextureFilePath)
{
this.Shader = Shader;
Texture = new Texture(TextureFilePath);
}
}
} |
namespace Puppeteer.Core.Configuration
{
public class WorldStateDescription
{
public WorldStateDescription()
{
}
public WorldStateDescription(WorldStateDescription _worldStateDescription)
{
Key = _worldStateDescription.Key;
Value = _worldStateDescription.Value;
}
public string Key = string.Empty;
public object Value = null;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pot : MonoBehaviour
{
private Animator anim;
private AudioSource audioSource;
private BoxCollider2D boxCollider;
void Start()
{
anim = GetComponent<Animator>();
audioSource = GetComponent<AudioSource>();
boxCollider = GetComponent<BoxCollider2D>();
}
public void Smash()
{
audioSource.time = 0.4f;
audioSource.Play();
anim.SetBool("smash", true);
StartCoroutine(BreakCo());
}
IEnumerator BreakCo()
{
boxCollider.enabled = false;
yield return new WaitForSeconds(0.55f);
audioSource.Stop();
gameObject.SetActive(false);
}
}
|
using UnityEngine;
public class PowerUps : MonoBehaviour
{
public Sprite[] powerUpsStatic;
public GameObject[] powerUpsAnimated;
bool inGround;
SpriteRenderer sr;
private Movimiento2 m2;
private void Awake()
{
sr = GetComponent<SpriteRenderer>();
m2 = FindObjectOfType<Movimiento2>();
}
// Start is called before the first frame update
void Start()
{
int aleatory = Random.Range(0, 2);
if (aleatory == 0)
{
sr.sprite = powerUpsStatic[Random.Range(0, powerUpsStatic.Length)];
gameObject.name = sr.sprite.name;
}
}
// Update is called once per frame
void Update()
{
if (!inGround)
{
transform.position += Vector3.down * Time.deltaTime * 2;
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "Abajo")
{
inGround = true;
Destroy(gameObject, 5);
}
if (other.gameObject.tag == "Jugador")
{
if (gameObject.name.Equals("CintaVelocidad"))
{
m2.Speed();
}
if (gameObject.name.Equals("Escopeta"))
{
m2.Speed();
}
Destroy(gameObject);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SinglePageApplication;
using SinglePageApplication.Controllers;
namespace SinglePageApplication.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void PercentOfCPULoadIsReturns()
{
HomeController controller = new HomeController();
float percent;
float.TryParse(controller.GetPercentOfCPULoad().Data.ToString(), out percent);
Assert.IsTrue((percent > 0 && percent < 100));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using DelftTools.Utils.Collections.Generic;
using GeoAPI.Extensions.Feature;
using GeoAPI.Extensions.Networks;
using GeoAPI.Geometries;
using DelftTools.Utils.Collections;
namespace GeoAPI.Extentions.Tests.Network
{
public class TestNetwork : INetwork
{
private IEventedList<INode> vertices = new EventedList<INode>();
private IEventedList<IBranch> edges = new EventedList<IBranch>();
public IEventedList<INode> Nodes
{
get { return vertices; }
set { vertices = value; }
}
public IEventedList<IBranchFeature> BranchFeatures
{
get { throw new NotImplementedException(); }
}
public IEventedList<INodeFeature> NodeFeatures
{
get { throw new NotImplementedException(); }
}
public IEventedList<IBranch> Branches
{
get { return edges; }
set { edges = value; }
}
public TestNetwork()
{
Branches.CollectionChanging += Branches_CollectionChanging;
}
public bool IsVerticesEmpty
{
get { return (0 == vertices.Count); }
}
public int VertexCount
{
get { return vertices.Count; }
}
public IEnumerable<INode> Vertices
{
get { return vertices; }
}
public bool ContainsVertex(INode node)
{
return vertices.Contains(node);
}
public bool IsDirected { get { return true; } }
public bool AllowParallelEdges { get { return true; } }
public bool IsEdgesEmpty
{
get { return (0 == edges.Count); }
}
public int EdgeCount
{
get { return edges.Count; }
}
public IEnumerable<IBranch> Edges
{
get { return edges; }
}
public bool ContainsEdge(IBranch edge)
{
return edges.Contains(edge);
}
public IEnumerable<IBranch> AdjacentEdges(INode v)
{
return v.IncomingBranches.Concat(v.OutgoingBranches);
}
public int AdjacentDegree(INode v)
{
throw new System.NotImplementedException();
}
public bool IsAdjacentEdgesEmpty(INode v)
{
throw new System.NotImplementedException();
}
public IBranch AdjacentEdge(INode v, int index)
{
throw new System.NotImplementedException();
}
public bool ContainsEdge(INode source, INode target)
{
throw new System.NotImplementedException();
}
// not relevant for this test
public long Id { get; set; }
public IGeometry Geometry { get; set; }
public IFeatureAttributeCollection Attributes { get; set; }
public string Name { get; set; }
public object Clone()
{
throw new NotImplementedException();
}
private void Branches_CollectionChanging(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
if (sender == Branches)
{
if (e.Item is TestBranch)
{
var branch = (TestBranch)e.Item;
if (branch.Network != this)
{
branch.Network = this;
}
}
}
break;
}
}
}
} |
namespace LAB02.Tools.Navigation
{
internal enum ViewType
{
EnterInfo,
ShowInfo
}
interface INavigationModel
{
void Navigate(ViewType viewType);
}
} |
using System;
using Utilities;
namespace EddiEvents
{
[PublicAPI]
public class CarrierPadsLockedEvent : Event
{
public const string NAME = "Carrier pads locked";
public const string DESCRIPTION = "Triggered when your fleet carrier locks landing pads prior to jumping";
public static CarrierPadsLockedEvent SAMPLE = new CarrierPadsLockedEvent(DateTime.UtcNow, 3700357376);
// These properties are not intended to be user facing
public long carrierId { get; private set; }
public CarrierPadsLockedEvent(DateTime timestamp, long carrierId) : base(timestamp, NAME)
{
this.carrierId = carrierId;
}
}
} |
using AutomationFramework.Enums;
using AutomationFramework.Helpers;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutomationFramework.Extensions
{
public static class LocatorExtensions
{
/// <summary>
/// From the locator to selenium by converter.
/// </summary>
/// <example>Using standard method FindElement, even we have locator as ElementLocator: <code>
/// private readonly ElementLocator searchTextbox = new ElementLocator(Locator.Id, "SearchTextBoxId");
/// this.Driver.FindElement(locator.ToBy());
/// </code> </example>
/// <param name="locator">The element locator.</param>
/// <returns>The Selenium By</returns>
public static By ToBy(this ElementLocator locator)
{
By by;
switch (locator.Kind)
{
case Locator.Id:
by = By.Id(locator.Value);
break;
case Locator.ClassName:
by = By.ClassName(locator.Value);
break;
case Locator.CssSelector:
by = By.CssSelector(locator.Value);
break;
case Locator.LinkText:
by = By.LinkText(locator.Value);
break;
case Locator.Name:
by = By.Name(locator.Value);
break;
case Locator.PartialLinkText:
by = By.PartialLinkText(locator.Value);
break;
case Locator.TagName:
by = By.TagName(locator.Value);
break;
case Locator.XPath:
by = By.XPath(locator.Value);
break;
default:
by = By.Id(locator.Value);
break;
}
return by;
}
}
}
|
namespace WinFormsMvpExample.Navigation
{
public static class NavigationService
{
public static BaseNavigator Navigator { get; set; }
}
}
|
using System.Threading.Tasks;
using CryptoLab.Infrastructure.Commands;
using CryptoLab.Infrastructure.Commands.Auth;
namespace CryptoLab.Infrastructure.Handlers.User
{
public class AuthHandler : ICommandHandler<AuthCommand>
{
public AuthHandler()
{
}
public async Task HandlerAsync(AuthCommand command)
{
await Task.CompletedTask;
}
}
} |
using System;
using System.Collections.Generic;
namespace AuctionMaster.App.Model
{
public partial class ScheduledTaskFrequency
{
public ScheduledTaskFrequency()
{
ScheduledTask = new HashSet<ScheduledTask>();
}
public int Id { get; set; }
public string Nome { get; set; }
public virtual ICollection<ScheduledTask> ScheduledTask { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExampleTimerUsage : MonoBehaviour {
Timer timer;
// Use this for initialization
void Start () {
// Create the timer
timer = new Timer();
// Register for the events
timer.OnTimeUp += HandleTimeUp;
timer.OnSecondsChanged += HandleSecondsChanged;
// Start the timer
timer.SetTimer(30);
timer.StartTimer();
}
// Update is called once per frame
void FixedUpdate () {
timer.Update();
}
void HandleTimeUp()
{
Debug.Log("Time is up!");
}
void HandleSecondsChanged(int secondsRemaining)
{
Debug.Log("Seconds Remaining: " + secondsRemaining);
}
}
|
using UnityEngine;
using System.Collections;
public class ExplosionScript : MonoBehaviour {
public GameObject player1;
public GameObject player2;
// Listen and change the health variables
public GameObject healthObj;
public PlayerHealth healthScript;
// Use this for initialization
void Start () {
player1 = GameObject.Find("Player1");
player2 = GameObject.Find("Player2");
healthObj = GameObject.Find("GameController");
healthScript = healthObj.GetComponent<PlayerHealth>();
}
// Update is called once per frame
void Update () {
if (transform.localScale.x < 5)
{// Scale up the object
transform.localScale += new Vector3(1, 1, 1);
}
else
{
Destroy(this.gameObject);
}
}
// Touches any of the player
void OnTriggerEnter(Collider hit)
{
if (hit.gameObject.tag == "PlayerOneBox")
{
healthScript.player1Health -= 10;
}
if (hit.gameObject.tag == "PlayerTwoBox")
{
healthScript.player2Health -= 10;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ScoreOrcsManager : MonoBehaviour
{
public static ScoreOrcsManager instance;
public TextMeshProUGUI text;
public int score;
// Start is called before the first frame update
void Start()
{
if (instance == null)
{
instance = this;
}
}
public void ChangeScore(int orcsValue)
{
score += orcsValue;
text.text = score.ToString() + " / 10";
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShipDefinition : ScriptableObject {
public string shipName;
public GameObject shipPrefab;
public Sprite shipIcon;
public float shipPrice;
public bool isBought;
public bool isUsed;
#if UNITY_EDITOR
[UnityEditor.MenuItem ("Tools/Create new ship")]
public static void CreateObject () {
ShipDefinition asset = (ShipDefinition)ScriptableObject.CreateInstance (typeof(ShipDefinition));
UnityEditor.AssetDatabase.CreateAsset (asset, "Assets/ShipDefinitions/New Ship.asset");
UnityEditor.AssetDatabase.SaveAssets ();
UnityEditor.EditorUtility.FocusProjectWindow ();
UnityEditor.Selection.activeObject = asset;
}
#endif
} |
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Client.Features.JobService.Models
{
public class PathCompareValue
{
[PrimaryKey]
public Guid Id { get; set; }
public string FullFile { get; set; }
public string Hash { get; set; }
public string FileName { get; set; }
public string Directory { get; set; }
public string Extension { get; set; }
public DateTime LastChange { get; set; }
public DateTime FileCreated { get; set; }
public DateTime? FileModified { get; set; }
public long FileSize { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class ABC121D{
public static void Main(){
var AB = Console.ReadLine().Split().Select(int.Parse).ToList();
var list = new List<char[]>();
foreach(var n in Enumerable.Range(AB[0],AB[0]-AB[1])){
string str = Convert.ToString(n, 2).ToCharArray();
}
var ans = new char[list.Max(x=>x.Count())];
foreach(var n in list){
foreach(var s in Enumerable.Range(0,n.Count())){
if(n[s] == '1'&&ans[n.Count()-(s+1)] == '0'){
ans[n.Count()-(s+1)] = 1;
}
else if(n[s] == '0'&&ans[n.Count()-(s+1)] == '1'){
ans[n.Count()-(s+1)] = 1;
}
else if(n[s] == '1'&&ans[n.Count()-(s+1)] == '1'){
ans[n.Count()-(s+1)] = 0;
}
else if(n[s] == '0'&&ans[n.Count()-(s+1)] == '0'){
ans[n.Count()-(s+1)] = 0;
}
}
}
foreach(var n in ans)Console.WriteLine(n);
}
} |
using System;
using FluentAssertions;
using HiLoSocket.CommandFormatter;
using NUnit.Framework;
using Ploeh.AutoFixture;
using ProtoBuf;
using Shouldly;
namespace HiLoSocketTests.CommandFormatter.Implements
{
[TestFixture]
[Category( "ProtobufCommandFormatterTests" )]
public class ProtobufCommandFormatterTests
{
[Test]
public void Deserialize_NullInput_ThrowsArgumentNullException( )
{
var formatter = FormatterFactory<ProtobufDataObject>.CreateFormatter( FormatterType.ProtobufFormatter );
var fixture = new Fixture( );
fixture.Register<byte[ ]>( ( ) => null );
var input = fixture.Create<byte[ ]>( );
Should.Throw<ArgumentNullException>(
( ) => formatter.Deserialize( input ) );
}
[Test]
public void Deserialize_ZeroLengthInput_ThrowsArgumentException( )
{
var formatter = FormatterFactory<ProtobufDataObject>.CreateFormatter( FormatterType.ProtobufFormatter );
var fixture = new Fixture
{
RepeatCount = 0
};
var input = fixture.Create<byte[ ]>( );
Should.Throw<ArgumentException>(
( ) => formatter.Deserialize( input ) );
}
[Test]
public void Serialize_NullInput_ThrowsArgumentNullException( )
{
var formatter = FormatterFactory<ProtobufDataObject>.CreateFormatter( FormatterType.ProtobufFormatter );
var fixture = new Fixture( );
fixture.Register<ProtobufDataObject>( ( ) => null );
var input = fixture.Create<ProtobufDataObject>( );
Should.Throw<ArgumentNullException>(
( ) => formatter.Serialize( input ) );
}
[Test]
public void SerializeAndDeserialize_ProtobufDataObject_ShouldBeEqual( )
{
var formatter = FormatterFactory<ProtobufDataObject>.CreateFormatter( FormatterType.ProtobufFormatter );
var fixture = new Fixture( );
var expected = fixture.Create<ProtobufDataObject>( );
var serializedResult = formatter.Serialize( expected );
var actual = formatter.Deserialize( serializedResult );
actual.ShouldBeEquivalentTo( expected );
}
public void SerializeAndDeserialize_String_ShouldBeEqual( )
{
var formatter = FormatterFactory<string>.CreateFormatter( FormatterType.ProtobufFormatter );
var fixture = new Fixture( );
var expected = fixture.Create<string>( );
var serializedResult = formatter.Serialize( expected );
var actual = formatter.Deserialize( serializedResult );
actual.ShouldBeEquivalentTo( expected );
}
[ProtoContract]
public class ProtobufDataObject
{
[ProtoMember( 1 )]
public int Age { get; set; }
[ProtoMember( 2 )]
public Guid Id { get; }
[ProtoMember( 3 )]
public string Name { get; set; }
public ProtobufDataObject( Guid id )
{
Id = id;
}
private ProtobufDataObject( )
{
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace com.zhifez.seagj {
public class UI_Main_Connections : Base {
public Text[] labels;
public Text instructSelectTm;
public Text instructSelectLink;
private int _selectionIndex = 0;
private int selectionIndex {
get { return _selectionIndex; }
set {
_selectionIndex = value;
int _maxLength = 0;
if ( activeTm == null ) {
foreach ( TransmissionMachine tm in GAME.tmMachines ) {
if ( tm.gameObject.activeSelf ) {
++_maxLength;
}
}
}
else {
foreach ( SateliteDish sd in GAME.satDishes ) {
if ( sd.enabled ) {
++_maxLength;
}
}
}
if ( _selectionIndex < 0 ) {
if ( activeTm == null ) {
_selectionIndex = _maxLength - 1;
}
else {
_selectionIndex = System.Array.IndexOf ( GAME.tmMachines, activeTm );
activeTm = null;
}
}
else if ( _selectionIndex >= _maxLength ) {
_selectionIndex = 0;
}
if ( activeTm == null ) {
instructSelectTm.text = "press A/D or Arrow Left/Right keys to choose a machine";
instructSelectTm.text += "\npress S or Arrow Down key to select " + GAME.tmMachines[ _selectionIndex ].name;
}
}
}
private TransmissionMachine _activeTm;
private TransmissionMachine activeTm {
get { return _activeTm; }
set {
_activeTm = value;
instructSelectTm.gameObject.SetActive ( _activeTm == null );
instructSelectLink.gameObject.SetActive ( _activeTm != null );
}
}
//--------------------------------------------------
// private
//--------------------------------------------------
//--------------------------------------------------
// public
//--------------------------------------------------
//--------------------------------------------------
// protected
//--------------------------------------------------
protected void OnEnable () {
if ( GAME != null ) {
activeTm = null;
selectionIndex = 0;
}
}
protected void Update () {
if ( activeTm == null ) {
if ( Input.GetKeyDown ( KeyCode.A )
|| Input.GetKeyDown ( KeyCode.LeftArrow ) ) {
AudioController.Play ( "ui_btn_direction" );
--selectionIndex;
}
if ( Input.GetKeyDown ( KeyCode.D )
|| Input.GetKeyDown ( KeyCode.RightArrow ) ) {
AudioController.Play ( "ui_btn_direction" );
++selectionIndex;
}
if ( Input.GetKeyDown ( KeyCode.S )
|| Input.GetKeyDown ( KeyCode.DownArrow ) ) {
AudioController.Play ( "ui_btn_direction" );
activeTm = GAME.tmMachines[ selectionIndex ];
selectionIndex = 0;
}
}
else {
if ( Input.GetKeyDown ( KeyCode.W )
|| Input.GetKeyDown ( KeyCode.UpArrow ) ) {
AudioController.Play ( "ui_btn_direction" );
--selectionIndex;
}
if ( Input.GetKeyDown ( KeyCode.S )
|| Input.GetKeyDown ( KeyCode.DownArrow ) ) {
AudioController.Play ( "ui_btn_direction" );
++selectionIndex;
}
if ( Input.GetKeyDown ( KeyCode.J )
|| Input.GetKeyDown ( KeyCode.Z ) ) {
// link or unlink
AudioController.Play ( "ui_btn_toggle" );
SateliteDish sd = GAME.satDishes[ selectionIndex ];
bool _isLinked = activeTm.SateliteDishIsLinked ( sd );
if ( _isLinked ) {
activeTm.UnlinkSateliteDish ( sd );
}
else {
activeTm.LinkSateliteDish ( sd, 0f, 0f );
}
}
}
for ( int a=0; a<GAME.tmMachines.Length; ++a ) {
labels[a].text = "";
TransmissionMachine tm = GAME.tmMachines[a];
if ( !tm.gameObject.activeSelf ) {
continue;
}
if ( activeTm == tm ) {
labels[a].text = "<b>" + tm.name + "</b>";
}
else if ( activeTm == null && selectionIndex == a ) {
labels[a].text = "> " + tm.name;
}
else {
labels[a].text += tm.name;
}
for ( int b=0; b<GAME.satDishes.Length; ++b ) {
SateliteDish sd = GAME.satDishes[b];
if ( !sd.enabled ) {
continue;
}
labels[a].text += "\n ";
if ( activeTm == tm
&& selectionIndex == b ) {
labels[a].text += "> ";
}
bool _isLinked = tm.SateliteDishIsLinked ( sd );
labels[a].text += ( _isLinked ? "[X] " : "[] " ) + sd.name;
}
}
}
}
} |
using System;
using System.Collections.Generic;
using Tweetinvi.Core.Controllers;
using Tweetinvi.Core.Factories;
using Tweetinvi.Core.Injectinvi;
using Tweetinvi.Models;
using Tweetinvi.Models.DTO;
using Tweetinvi.Parameters;
namespace Tweetinvi
{
/// <summary>
/// Receive and send private messages between users.
/// </summary>
public static class Message
{
[ThreadStatic]
private static IMessageFactory _messageFactory;
/// <summary>
/// Factory used to create Messages
/// </summary>
public static IMessageFactory MessageFactory
{
get
{
if (_messageFactory == null)
{
Initialize();
}
return _messageFactory;
}
}
[ThreadStatic]
private static IMessageController _messageController;
/// <summary>
/// Controller handling any Message request
/// </summary>
public static IMessageController MessageController
{
get
{
if (_messageController == null)
{
Initialize();
}
return _messageController;
}
}
private static IFactory<IMessagesReceivedParameters> _messageGetLatestsReceivedRequestParametersFactory;
private static IFactory<IMessagesSentParameters> _messageGetLatestsSentRequestParametersFactory;
private static IFactory<IPublishMessageParameters> _messagePublishParametersFactory;
static Message()
{
Initialize();
_messageGetLatestsReceivedRequestParametersFactory = TweetinviContainer.Resolve<IFactory<IMessagesReceivedParameters>>();
_messageGetLatestsSentRequestParametersFactory = TweetinviContainer.Resolve<IFactory<IMessagesSentParameters>>();
_messagePublishParametersFactory = TweetinviContainer.Resolve<IFactory<IPublishMessageParameters>>();
}
private static void Initialize()
{
_messageFactory = TweetinviContainer.Resolve<IMessageFactory>();
_messageController = TweetinviContainer.Resolve<IMessageController>();
}
// Factory
/// <summary>
/// Get an existing message from its id
/// </summary>
public static IMessage GetExistingMessage(long messageId)
{
return MessageFactory.GetExistingMessage(messageId);
}
// Controller
/// <summary>
/// Get the latest messages received
/// </summary>
public static IEnumerable<IMessage> GetLatestMessagesReceived(int maximumMessages = TweetinviConsts.MESSAGE_GET_COUNT)
{
return MessageController.GetLatestMessagesReceived(maximumMessages);
}
/// <summary>
/// Get the latest messages received
/// </summary>
public static IEnumerable<IMessage> GetLatestMessagesReceived(IMessagesReceivedParameters messagesReceivedParameters)
{
return MessageController.GetLatestMessagesReceived(messagesReceivedParameters);
}
/// <summary>
/// Get the latest messages sent
/// </summary>
public static IEnumerable<IMessage> GetLatestMessagesSent(int maximumMessages = TweetinviConsts.MESSAGE_GET_COUNT)
{
return MessageController.GetLatestMessagesSent(maximumMessages);
}
/// <summary>
/// Get the latest messages sent
/// </summary>
public static IEnumerable<IMessage> GetLatestMessagesSent(IMessagesSentParameters messagesSentParameters)
{
return MessageController.GetLatestMessagesSent(messagesSentParameters);
}
/// <summary>
/// Publish a message
/// </summary>
public static IMessage PublishMessage(string text, IUserIdentifier recipient)
{
return MessageController.PublishMessage(text, recipient);
}
/// <summary>
/// Publish a message
/// </summary>
public static IMessage PublishMessage(string text, long recipientId)
{
return MessageController.PublishMessage(text, recipientId);
}
/// <summary>
/// Publish a message
/// </summary>
public static IMessage PublishMessage(string text, string recipientScreenName)
{
return MessageController.PublishMessage(text, recipientScreenName);
}
/// <summary>
/// Publish a message
/// </summary>
public static IMessage PublishMessage(IPublishMessageParameters parameters)
{
return MessageController.PublishMessage(parameters);
}
/// <summary>
/// Destroy a message
/// </summary>
public static bool DestroyMessage(IMessage message)
{
return MessageController.DestroyMessage(message);
}
/// <summary>
/// Destroy a message
/// </summary>
public static bool DestroyMessage(IMessageDTO messageDTO)
{
return MessageController.DestroyMessage(messageDTO);
}
/// <summary>
/// Destroy a message
/// </summary>
public static bool DestroyMessage(long messageId)
{
return MessageController.DestroyMessage(messageId);
}
// Generate message from DTO
public static IMessage GenerateMessageFromMessageDTO(IMessageDTO messageDTO)
{
return MessageFactory.GenerateMessageFromMessageDTO(messageDTO);
}
public static IEnumerable<IMessage> GenerateMessagesFromMessagesDTO(IEnumerable<IMessageDTO> messagesDTO)
{
return MessageFactory.GenerateMessagesFromMessagesDTO(messagesDTO);
}
public static string ToJson(IMessage message)
{
return message.ToJson();
}
public static string ToJson(IMessageDTO message)
{
return message.ToJson();
}
public static IMessage FromJson(string json)
{
return MessageFactory.GenerateMessageFromJson(json);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace 用反射_Attribute控制属性的值
{
class Program
{
static void Main(string[] args)
{
Person p = new Person() { Name = "haha", Email = "sss@qq.com", Phone = "15000000000" };
string errMsg = GetErrorMsg.Check<Person>(p);
Console.WriteLine(errMsg);
Console.ReadKey();
}
}
}
|
using gView.GraphicsEngine.Abstraction;
using gView.GraphicsEngine.GdiPlus.Extensions;
using System.Drawing.Drawing2D;
namespace gView.GraphicsEngine.GdiPlus
{
internal class GdiLinearGradientBrush : IBrush
{
private LinearGradientBrush _brush;
public GdiLinearGradientBrush(CanvasRectangleF rect, ArgbColor col1, ArgbColor col2, float angle)
{
_brush = new LinearGradientBrush(rect.ToGdiRectangleF(), col1.ToGdiColor(), col2.ToGdiColor(), angle);
}
public object EngineElement => _brush;
public ArgbColor Color { get; set; }
public void Dispose()
{
if (_brush != null)
{
_brush.Dispose();
_brush = null;
}
}
}
} |
using Microsoft.Extensions.DependencyInjection;
using Eda.Extensions.DependencyInjection;
namespace Eda.Integrations.Delivery.DependencyInjection
{
/// <inheritdoc />
/// <summary>
/// Base class for delivery application block.
/// </summary>
public abstract class DeliveryApplicationBlock : IApplicationBlock
{
#region IApplicationBlock
/// <inheritdoc />
public void AddTo(IServiceCollection services)
{
var deliveryServices = new DeliveryServiceCollection(services);
ConfigureDeliveryServices(deliveryServices);
services.AddSingleton(serviceProvider => new DeliveryServiceProvider(serviceProvider));
}
#endregion
#region Methods
/// <summary>
/// Configures selivery services.
/// </summary>
/// <param name="services">Delivery services collection.</param>
protected abstract void ConfigureDeliveryServices(DeliveryServiceCollection services);
#endregion
}
} |
using System;
namespace Beeffective.Extensions
{
static class BooleanExtensions
{
public static bool IfTrue(this bool value, Action action)
{
if (value) action();
return value;
}
public static bool IfFalse(this bool value, Action action)
{
if (!value) action();
return value;
}
public static bool Call(this bool value, Action action)
{
if (value) action();
return value;
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ReadyController : MonoBehaviour {
public Image readyP1;
public Image readyP2;
public Text countDown;
private bool p1Ready;
private bool p2Ready;
private int countingDown;
// Update is called once per frame
void FixedUpdate () {
if (Input.GetKeyDown (KeyCode.T) || Input.GetKeyDown ("joystick 1 button 0")) {
p1Ready = !p1Ready; // enable / disable ready splash
readyP1.enabled = p1Ready; // show the ready splash
}
if (Input.GetKeyDown (KeyCode.Keypad0) || Input.GetKeyDown (KeyCode.Alpha0) || Input.GetKeyDown ("joystick 2 button 0")) {
p2Ready = !p2Ready;
readyP2.enabled = p2Ready;
}
if (p1Ready && p2Ready)
countDown.enabled = true;
if (countingDown == 0 && p1Ready && p2Ready) { // dont start multiple timers
countingDown++;
StartCoroutine (startCountDown ()); // both players are ready, start countdown
}
else if (!p1Ready || !p2Ready) {
countDown.enabled = false; // someone unreadied, stoppit
}
}
private IEnumerator startCountDown() { // start 3 sec countdown to game start (while p1 & p2 are ready)
for (int i = 35; i >= 5; i--) {
if (countingDown == 0 || !p1Ready || !p2Ready) // if they change their minds, break out
break;
if (countingDown == 1 && p1Ready && p2Ready)
countDown.text = "" + i / 10; // update text
if (p1Ready && p2Ready && i <= 5) // timer's up & we're still ready, load the game
Application.LoadLevel ("Transition");
yield return new WaitForSeconds (.1f);
}
countingDown--;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Node : MonoBehaviour {
[SerializeField]
private GameObject _tower;
[SerializeField]
private GameControler control;
public Material towerBuild;
public Material grass;
public bool SetTower(GameObject tower)
{
if(control.money >= tower.GetComponent<Tower>().cost)
{
_tower = tower;
control.money -= tower.GetComponent<Tower>().cost;
GetComponent<Renderer>().material = towerBuild;
return true;
}
else
{
Debug.Log("NIE MASZ pieniedy");
return false;
}
}
public GameObject GetTower()
{
return _tower;
}
public void DestroyTower()
{
Destroy(_tower);
_tower = null;
GetComponent<Renderer>().material = grass;
}
// Use this for initialization
void Start () {
control = GetComponentInParent<GameControler>();
}
// Update is called once per frame
void Update () {
}
}
|
using UnityEngine;
using UnityEngine.UI;
public class NodeTrigger : MonoBehaviour
{
// Setup the prompt for the node
public GameObject bluePrompt;
public Image blueRing;
public GameObject greenPrompt;
public Image greenRing;
public float maxTime;
public float leftTime;
private bool hasActivatedBluePrompt = false;
private bool hasActivatedGreenPrompt = false;
// Setup the checkers for node's status
public bool isStartNode = false;
public bool isEndNode = false;
public bool isInNode = false;
public bool isOnNode = false;
// Setup the variables to build functions
private bool isPressingnode = false;
private float pressingTime = 0;
private bool isDetectingPointer = false;
private CombatGenerator combatGenerator;
private void Start()
{
combatGenerator = GameObject.FindWithTag("MinigameManager").GetComponent<CombatGenerator>();
}
private void Update()
{
ActivateBluePrompt();
ActivateGreenPrompt();
}
public void ActivateBluePrompt()
{
if (isStartNode)
{
if (!hasActivatedBluePrompt)
{
bluePrompt.SetActive(true);
maxTime = combatGenerator.clickTime;
hasActivatedBluePrompt = true;
}
leftTime = combatGenerator.combatTimer;
blueRing.fillAmount = leftTime / maxTime;
}
}
public void ActivateGreenPrompt()
{
if (isEndNode)
{
if (!hasActivatedGreenPrompt)
{
greenPrompt.SetActive(true);
maxTime = combatGenerator.gapTime;
hasActivatedGreenPrompt = true;
}
leftTime = combatGenerator.combatTimer;
greenRing.fillAmount = leftTime / maxTime;
}
}
public void DeactivatePrompt()
{
bluePrompt.SetActive(false);
hasActivatedBluePrompt = false;
greenPrompt.SetActive(false);
hasActivatedGreenPrompt = false;
}
private void PointerDown(bool isnodeDown)
{
isPressingnode = isnodeDown;
if (isPressingnode)
{
this.isInNode = true;
if (isStartNode)
{
combatGenerator.hasStartedCombat = true;
}
else
{
combatGenerator.hasStartedCombat = false;
}
pressingTime = Time.time;
//Debug.Log("Start to press a node.");
}
else if (pressingTime != 0)
{
this.isInNode = false;
combatGenerator.hasStartedCombat = false;
pressingTime = 0;
//Debug.Log("Cancel pressing a node.");
}
}
private void PointerOn(bool isnodeOn)
{
isDetectingPointer = isnodeOn;
if (isDetectingPointer)
{
this.isOnNode = true;
if (isEndNode)
{
combatGenerator.hasEndedCombat = true;
}
else
{
combatGenerator.hasEndedCombat = false;
}
//Debug.Log("Detect a pointer on node.");
}
else if (!isDetectingPointer)
{
this.isOnNode = false;
combatGenerator.hasEndedCombat = false;
}
}
}
|
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Moq;
using Pobs.Comms;
using Pobs.Domain.Entities;
using Pobs.Tests.Integration.Helpers;
using Pobs.Web.Models.Questions;
using Xunit;
namespace Pobs.Tests.Integration.Questions
{
public class ReportAnswerTests : IDisposable
{
private string _generateUrl(int questionId, int answerId) =>
$"/api/questions/{questionId}/answers/{answerId}/report";
private readonly User _questionUser;
private readonly User _reportingUser;
private readonly Question _question;
private readonly Answer _answer;
private readonly ReportModel _payload = new ReportModel { Reason = Utils.GenerateRandomString(10) };
public ReportAnswerTests()
{
_questionUser = DataHelpers.CreateUser();
_reportingUser = DataHelpers.CreateUser();
_question = DataHelpers.CreateQuestions(_questionUser, 1, _questionUser, 1).Single();
_answer = _question.Answers.Single();
}
[Fact]
public async Task Authenticated_ShouldSendEmail()
{
var mockEmailSender = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(mockEmailSender.Object))
using (var client = server.CreateClient())
{
client.AuthenticateAs(_reportingUser.Id);
var url = _generateUrl(_question.Id, _answer.Id);
var response = await client.PostAsync(url, _payload.ToJsonContent());
response.EnsureSuccessStatusCode();
mockEmailSender.Verify(x =>
x.SendReportAnswerEmail(_reportingUser.Id, _payload.Reason, _question.Id, _question.Text, _answer.Id, _answer.Text),
Times.Once);
}
}
[Fact]
public async Task NoReason_ShouldGetBadRequest()
{
var mockEmailSender = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(mockEmailSender.Object))
using (var client = server.CreateClient())
{
client.AuthenticateAs(_reportingUser.Id);
var url = _generateUrl(_question.Id, _answer.Id);
var response = await client.PostAsync(url, new ReportModel().ToJsonContent());
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var content = await response.Content.ReadAsStringAsync();
Assert.Equal("Reason is required.", content);
mockEmailSender.Verify(x =>
x.SendReportAnswerEmail(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>()),
Times.Never);
}
}
[Fact]
public async Task NotAuthenticated_ShouldBeDenied()
{
var mockEmailSender = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(mockEmailSender.Object))
using (var client = server.CreateClient())
{
var url = _generateUrl(_question.Id, _answer.Id);
var response = await client.PostAsync(url, _payload.ToJsonContent());
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
mockEmailSender.Verify(x =>
x.SendReportAnswerEmail(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>()),
Times.Never);
}
}
[Fact]
public async Task UnknownQuestionId_ShouldReturnNotFound()
{
var mockEmailSender = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(mockEmailSender.Object))
using (var client = server.CreateClient())
{
client.AuthenticateAs(_reportingUser.Id);
var url = _generateUrl(0, _answer.Id);
var response = await client.PostAsync(url, _payload.ToJsonContent());
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
mockEmailSender.Verify(x =>
x.SendReportAnswerEmail(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>()),
Times.Never);
}
}
[Fact]
public async Task UnknownAnswerId_ShouldReturnNotFound()
{
var mockEmailSender = new Mock<IEmailSender>();
using (var server = new IntegrationTestingServer(mockEmailSender.Object))
using (var client = server.CreateClient())
{
client.AuthenticateAs(_reportingUser.Id);
var url = _generateUrl(_question.Id, 0);
var response = await client.PostAsync(url, _payload.ToJsonContent());
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
mockEmailSender.Verify(x =>
x.SendReportAnswerEmail(It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>()),
Times.Never);
}
}
public void Dispose()
{
DataHelpers.DeleteUser(_questionUser.Id);
DataHelpers.DeleteUser(_reportingUser.Id);
}
}
}
|
using System;
namespace OrgMan.DomainObjects.Common
{
public class MemberInformationToMembershipDomainModel
{
public Guid UID { get; set; }
public Guid MembershipUID { get; set; }
public Guid MemberInformationUID { get; set; }
public MembershipDomainModel Membership { get; set; }
}
}
|
using _7DRL_2021.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _7DRL_2021.Results
{
class ActionChangeMomentum : IActionHasOrigin
{
public ICurio Origin { get; set; }
public int Momentum;
public bool Done => true;
public ActionChangeMomentum(ICurio origin, int momentum)
{
Origin = origin;
Momentum = momentum;
}
public void Run()
{
var player = Origin.GetBehavior<BehaviorPlayer>();
if (player != null)
{
player.Momentum.Amount = Math.Max(0, player.Momentum.Amount + Momentum);
}
}
}
}
|
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Plugins.DefaultTheme.Home
{
public class ItemStub
{
public string Name { get; set; }
public string Id { get; set; }
public string ImageTag { get; set; }
public ImageType ImageType { get; set; }
}
public class MoviesView : BaseView
{
public List<ItemStub> MovieItems { get; set; }
public List<ItemStub> BoxSetItems { get; set; }
public List<ItemStub> TrailerItems { get; set; }
public List<ItemStub> HDItems { get; set; }
public List<ItemStub> ThreeDItems { get; set; }
public List<ItemStub> FamilyMovies { get; set; }
public List<ItemStub> RomanceItems { get; set; }
public List<ItemStub> ComedyItems { get; set; }
public double FamilyMoviePercentage { get; set; }
public double HDMoviePercentage { get; set; }
public List<BaseItemDto> LatestTrailers { get; set; }
public List<BaseItemDto> LatestMovies { get; set; }
}
public class TvView : BaseView
{
public List<ItemStub> ShowsItems { get; set; }
public List<ItemStub> RomanceItems { get; set; }
public List<ItemStub> ComedyItems { get; set; }
public List<string> SeriesIdsInProgress { get; set; }
public List<BaseItemDto> LatestEpisodes { get; set; }
public List<BaseItemDto> NextUpEpisodes { get; set; }
public List<BaseItemDto> ResumableEpisodes { get; set; }
}
public class ItemByNameInfo
{
public string Name { get; set; }
public int ItemCount { get; set; }
}
public class GamesView : BaseView
{
public List<ItemStub> MultiPlayerItems { get; set; }
public List<BaseItemDto> GameSystems { get; set; }
public List<BaseItemDto> RecentlyPlayedGames { get; set; }
}
public class BaseView
{
public List<BaseItemDto> BackdropItems { get; set; }
public List<BaseItemDto> SpotlightItems { get; set; }
public List<BaseItemDto> MiniSpotlights { get; set; }
}
public class FavoritesView : BaseView
{
public List<BaseItemDto> Artists { get; set; }
public List<BaseItemDto> Movies { get; set; }
public List<BaseItemDto> Series { get; set; }
public List<BaseItemDto> Episodes { get; set; }
public List<BaseItemDto> Games { get; set; }
public List<BaseItemDto> Books { get; set; }
public List<BaseItemDto> Albums { get; set; }
public List<BaseItemDto> Songs { get; set; }
}
public static class ApiClientExtensions
{
public const string ComedyGenre = "comedy";
public const string RomanceGenre = "romance";
public const string FamilyGenre = "family";
public const double TopTvCommunityRating = 8.5;
public const double TopMovieCommunityRating = 8.2;
public static Task<TvView> GetTvView(this IApiClient apiClient, string userId, CancellationToken cancellationToken)
{
var url = apiClient.GetApiUrl("MBT/DefaultTheme/TV?userId=" + userId + "&ComedyGenre=" + ComedyGenre + "&RomanceGenre=" + RomanceGenre + "&TopCommunityRating=" + TopTvCommunityRating + "&NextUpEpisodeLimit=15&LatestEpisodeLimit=9&ResumableEpisodeLimit=3");
return apiClient.GetAsync<TvView>(url, cancellationToken);
}
public static Task<MoviesView> GetMovieView(this IApiClient apiClient, string userId, CancellationToken cancellationToken)
{
var url = apiClient.GetApiUrl("MBT/DefaultTheme/Movies?familyrating=pg&userId=" + userId + "&ComedyGenre=" + ComedyGenre + "&RomanceGenre=" + RomanceGenre + "&FamilyGenre=" + FamilyGenre + "&LatestMoviesLimit=16&LatestTrailersLimit=6");
return apiClient.GetAsync<MoviesView>(url, cancellationToken);
}
public static Task<FavoritesView> GetFavoritesView(this IApiClient apiClient, string userId, CancellationToken cancellationToken)
{
var url = apiClient.GetApiUrl("MBT/DefaultTheme/Favorites?userId=" + userId);
return apiClient.GetAsync<FavoritesView>(url, cancellationToken);
}
public static Task<GamesView> GetGamesView(this IApiClient apiClient, string userId, CancellationToken cancellationToken)
{
var url = apiClient.GetApiUrl("MBT/DefaultTheme/Games?userId=" + userId + "&RecentlyPlayedGamesLimit=3");
return apiClient.GetAsync<GamesView>(url, cancellationToken);
}
}
}
|
namespace TaxiService.Discount.Models
{
public class Coupon
{
public int CouponId { get; set; }
public string Code { get; set; }
public int Amount { get; set; }
public bool AlreadyUsed { get; set; }
}
}
|
using System.Security.Principal;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PatternsCore.Security;
using Rhino.Mocks;
namespace Pattern.Tests
{
[TestClass()]
public class RhinoMocksAtPlay
{
[TestMethod()]
public
void TestMethod1()
{
var mrepo = new MockRepository();
var user = mrepo.DynamicMock<IPrincipal>();
var permissionChecker = new CheckUserPermissions();
using (mrepo.Record())
{
SetupResult.For(user.IsInRole("test")).Return(true);
}
using (mrepo.Playback())
{
Assert.IsTrue(permissionChecker.HaveManagerRole(user));
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Bloodhound.Core.Model;
using Bloodhound.Models;
using Bloodhound.Core;
namespace Bloodhound.Controllers
{
public class OffendersController : Controller
{
private readonly BloodhoundContext _context;
public OffendersController(BloodhoundContext context)
{
_context = context;
}
// GET: Offenders
public async Task<IActionResult> Index()
{
return View(await _context.Offenders.ToListAsync());
}
// GET: Offenders/Details/5
public IActionResult Details(OffenderDetailModel model)
{
try
{
model.Initialize(this._context);
return View(model);
}
catch(EntityNotFoundException)
{
return NotFound();
}
}
// GET: Offenders/Create
public IActionResult Create()
{
return View();
}
// POST: Offenders/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("OffenderId,OffenderName,OffenderSummary")] Offender offender)
{
if (ModelState.IsValid)
{
_context.Add(offender);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(offender);
}
// GET: Offenders/Edit/5
public async Task<IActionResult> Edit(long? id)
{
if (id == null)
{
return NotFound();
}
var offender = await _context.Offenders.FindAsync(id);
if (offender == null)
{
return NotFound();
}
return View(offender);
}
// POST: Offenders/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(long id, [Bind("OffenderId,OffenderName,OffenderSummary")] Offender offender)
{
if (id != offender.OffenderId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(offender);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!OffenderExists(offender.OffenderId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(offender);
}
// GET: Offenders/Delete/5
public async Task<IActionResult> Delete(long? id)
{
if (id == null)
{
return NotFound();
}
var offender = await _context.Offenders
.FirstOrDefaultAsync(m => m.OffenderId == id);
if (offender == null)
{
return NotFound();
}
return View(offender);
}
// POST: Offenders/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(long id)
{
var offender = await _context.Offenders.FindAsync(id);
_context.p_Offender_Delete(offender.OffenderId);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool OffenderExists(long id)
{
return _context.Offenders.Any(e => e.OffenderId == id);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Ludotek.Api.Business;
using Ludotek.Api.Dao;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Swagger;
namespace Ludotek.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
/// <summary>
/// Ajout des dbContext de l'application
/// </summary>
private void EnregistrementContext(IServiceCollection services)
{
// Enregistrement du Context
services.AddScoped<Context>();
}
/// <summary>
/// Ajout des Business de l'application
/// </summary>
private void EnregistrementBusiness(IServiceCollection services)
{
// Enregistrement des Business
services.AddScoped(typeof(LudothequeBusiness));
services.AddScoped(typeof(TagBusiness));
services.AddScoped(typeof(ImportBusiness));
}
/// <summary>
/// Ajout des Dao de l'application
/// </summary>
private void EnregistrementDao(IServiceCollection services)
{
// Enregistrement des DAO
services.AddScoped(typeof(LudothequeDao));
services.AddScoped(typeof(TagDao));
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Gestion de la localisation des messages
services.Configure<RequestLocalizationOptions>(
opts =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("fr-FR"),
new CultureInfo("fr"),
};
opts.DefaultRequestCulture = new RequestCulture("fr");
// Formatting numbers, dates, etc.
opts.SupportedCultures = supportedCultures;
// UI strings that we have localized.
opts.SupportedUICultures = supportedCultures;
});
services.AddLocalization(options => options.ResourcesPath = "Resources");
// CORS
services.AddCors();
// MVC
services.AddMvc()
.AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; });
// Connexion à la BDD
services.AddDbContext<Context>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultDatabase")));
// Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Ludothèque", Version = "v1" });
});
EnregistrementContext(services);
EnregistrementBusiness(services);
EnregistrementDao(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//env.EnvironmentName = EnvironmentName.Development;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/error");
}
app.UseStatusCodePages();
app.UseStaticFiles();
// Localisation
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
// CORS
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseMvc();
// Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ludothèque V1");
});
}
}
}
|
/********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2001 *
* by the XIPHOPHORUS Company http://www.xiph.org/ *
********************************************************************
function: libvorbis codec headers
********************************************************************/
/* C#/.NET interop-port
*
* Copyright 2004 Klaus Prückl <klaus.prueckl@aon.at>
*/
using System;
using System.Runtime.InteropServices;
using Codecs.Interop.Ogg;
namespace Codecs.Interop.Vorbis
{
/// <summary>
/// vorbis_dsp_state buffers the current vorbis audio
/// analysis/synthesis state. The DSP state belongs to a specific
/// logical bitstream
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct vorbis_dsp_state
{
internal int analysisp;
internal IntPtr vi;
internal IntPtr pcm; // float **
internal IntPtr pcmret; // float **
internal int pcm_storage;
internal int pcm_current;
internal int pcm_returned;
internal int preextrapolate;
internal int eofflag;
internal int lW;
internal int W;
internal int nW;
internal int centerW;
internal long granulepos;
internal long sequence;
internal long glue_bits;
internal long time_bits;
internal long floor_bits;
internal long res_bits;
internal IntPtr backend_state; // void *
}
/// <summary>
/// </summary>
public class VorbisDspState : IDisposable
{
#region Variables
internal vorbis_dsp_state vorbis_dsp_state = new vorbis_dsp_state();
private VorbisInfo vi;
internal bool changed = true;
private bool initialized = false;
#endregion
#region Constructor(s) & Destructor
/// <summary>
/// </summary>
/// <param name="vi"></param>
public VorbisDspState(VorbisInfo vi)
{
this.vi = vi;
}
#endregion
#region Properties
/// <summary>
/// </summary>
public VorbisInfo Vi
{
get
{
if(this.changed)
{
this.vi.vorbis_info = (vorbis_info) Marshal.PtrToStructure(
this.vorbis_dsp_state.vi, typeof(vorbis_info));
this.changed = false;
}
return this.vi;
}
}
/// <summary>
/// </summary>
public int PcmStorage
{
get { return this.vorbis_dsp_state.pcm_storage; }
}
/// <summary>
/// </summary>
public int PcmCurrent
{
get { return this.vorbis_dsp_state.pcm_current; }
}
/// <summary>
/// </summary>
public long Sequence
{
get { return this.vorbis_dsp_state.sequence; }
}
#endregion
#region Vorbis PRIMITIVES: general ***************************************
#region Analysis
[DllImport(Vorbis.DllFile, CallingConvention = CallingConvention.Cdecl)]
private static extern int vorbis_analysis_init([In, Out] ref vorbis_dsp_state v, [In, Out] ref vorbis_info vi);
[DllImport(Vorbis.DllFile, CallingConvention = CallingConvention.Cdecl)]
private static extern int vorbis_analysis_init(IntPtr v, [In, Out] ref vorbis_info vi);
public static int AnalysisInit(VorbisDspState dspState, VorbisInfo info)
{
int retVal = vorbis_analysis_init(ref dspState.vorbis_dsp_state, ref info.vorbis_info);
dspState.changed = true;
dspState.initialized = true;
info.changed = true;
return retVal;
}
public static int AnalysisInit(IntPtr dspState, VorbisInfo info)
{
int retVal = vorbis_analysis_init(dspState, ref info.vorbis_info);
info.changed = true;
return retVal;
}
[DllImport(Vorbis.DllFile, CallingConvention = CallingConvention.Cdecl)]
private static extern int vorbis_analysis_headerout([In, Out] ref vorbis_dsp_state v,
[In, Out] ref vorbis_comment vc,
[Out] out ogg_packet op,
[Out] out ogg_packet op_comm,
[Out] out ogg_packet op_code);
[DllImport(Vorbis.DllFile, CallingConvention = CallingConvention.Cdecl)]
private static extern int vorbis_analysis_headerout(IntPtr v,
[In, Out] ref vorbis_comment vc,
[Out] out ogg_packet op,
[Out] out ogg_packet op_comm,
[Out] out ogg_packet op_code);
public static int HeaderOut(VorbisDspState dspState, VorbisComment comment, OggPacket header, OggPacket headerComm, OggPacket headerCode)
{
int retVal = vorbis_analysis_headerout(
ref dspState.vorbis_dsp_state,
ref comment.vorbis_comment,
out header.ogg_packet,
out headerComm.ogg_packet,
out headerCode.ogg_packet);
dspState.changed = true;
comment.changed = true;
header.changed = true;
headerCode.changed = true;
headerComm.changed = true;
return retVal;
}
public static int HeaderOut(IntPtr dspState, VorbisComment comment, OggPacket header, OggPacket headerComm, OggPacket headerCode)
{
int retVal = vorbis_analysis_headerout(
dspState,
ref comment.vorbis_comment,
out header.ogg_packet,
out headerComm.ogg_packet,
out headerCode.ogg_packet);
comment.changed = true;
header.changed = true;
headerCode.changed = true;
headerComm.changed = true;
return retVal;
}
#endregion
#region vorbis_dsp_clear
[DllImport(Vorbis.DllFile, CallingConvention=CallingConvention.Cdecl)]
private static extern void vorbis_dsp_clear([In,Out] ref vorbis_dsp_state v);
/// <summary>
/// </summary>
/// <param name="v"></param>
public static void Clear(VorbisDspState v)
{
vorbis_dsp_clear(ref v.vorbis_dsp_state);
v.changed = true;
v.initialized = false;
}
#endregion
#endregion
~VorbisDspState()
{
this.Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (this.initialized)
VorbisDspState.Clear(this);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
}
}
|
using System;
using org.ogre;
namespace PacmanOgre.Input
{
public class KeyboardEventArgs : EventArgs
{
public KeyboardEvent KeyboardEvent { get; set; }
}
public class InputManager : InputListener, IDisposable
{
public event EventHandler<KeyboardEventArgs> OnKeyPressed;
public event EventHandler<KeyboardEventArgs> OnKeyReleased;
public InputManager(IContext ctx)
{
}
public override bool keyPressed(KeyboardEvent evt)
{
OnKeyPressed?.Invoke(this, new KeyboardEventArgs() { KeyboardEvent = evt });
return false; // propgate further;
}
public override bool keyReleased(KeyboardEvent evt)
{
OnKeyReleased?.Invoke(this, new KeyboardEventArgs() { KeyboardEvent = evt });
return false; // propgate further;
}
public override bool mouseMoved(MouseMotionEvent evt)
{
return false; // propgate further;
}
public override bool mousePressed(MouseButtonEvent evt)
{
return false; // propgate further;
}
public override bool mouseReleased(MouseButtonEvent evt)
{
return false; // propgate further;
}
public override bool mouseWheelRolled(MouseWheelEvent evt)
{
return false; // propgate further;
}
public override bool touchMoved(TouchFingerEvent evt)
{
return false; // propgate further;
}
public override bool touchPressed(TouchFingerEvent evt)
{
return false; // propgate further;
}
public override bool touchReleased(TouchFingerEvent evt)
{
return false; // propgate further;
}
#region IDisposable Support
private bool disposedValue = false;
protected virtual new void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
base.Dispose();
}
disposedValue = true;
}
}
public new void Dispose() => Dispose(true);
#endregion
}
}
|
using System;
using Newtonsoft.Json;
using static Microsoft.UnifiedRedisPlatform.Core.Constants.Constant.LoggingConstants;
namespace Microsoft.UnifiedRedisPlatform.Core.Logging
{
public class LogConfiguration: ICloneable
{
public bool Enabled { get; set; }
public string LoggingStrategy { get; set; }
public int MinAggregatedItems { get; set; }
public int MaxLogInternalInSeconds { get; set; }
public int MaxRetryAttempt { get; set; }
public string LogKey { get; set; }
public LogConfiguration(bool enabled = true, string loggingStrategy = CacheAsideLogging, string logKey = DefaultLogKey, int maxRetryAttempty = 5, int minAggregatedItems = 10, int maxLogIntervalInSeconds = 300)
{
Enabled = enabled;
LoggingStrategy = loggingStrategy;
LogKey = logKey;
MaxRetryAttempt = maxRetryAttempty;
MinAggregatedItems = minAggregatedItems;
MaxLogInternalInSeconds = maxLogIntervalInSeconds;
}
public static LogConfiguration GetDefault()
{
return new LogConfiguration();
}
public object Clone()
{
var configurationStr = JsonConvert.SerializeObject(this);
return JsonConvert.DeserializeObject<LogConfiguration>(configurationStr);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Backend.Model.Pharmacies
{
public class Tender
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[Required]
public string QueueName { get; set; }
[Required]
public string RoutingKey { get; set; }
public bool IsClosed { get; set; }
public DateTime EndDate { get; set; }
public virtual List<TenderDrug> Drugs { get; set; }
public bool isValid()
{
if (Name == null || Name.Trim() == "")
return false;
if (EndDate == null || EndDate < DateTime.Now)
return false;
return true;
}
}
}
|
using System.Data.Entity;
namespace kidd.software.dotnet.shop.model
{
public static class DbSetExtension
{
public static void Clear<T>(this DbSet<T> obj)
where T : class
{
obj.RemoveRange(obj);
}
}
public class ShopContext : DbContext
{
public ShopContext(string databaseName) : base(databaseName)
{
}
public ShopContext() : base("Shop")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CustomerConfiguration());
modelBuilder.Configurations.Add(new OrderConfiguration());
}
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MoulaCodingChallenge.Data;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MoulaCodingChallenge.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
namespace MoulaCodingChallenge
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AccountContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
services.AddTransient<IAccountService, AccountService>();
services.AddTransient<IAccountRepository, AccountRepository>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer("Default", options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "moula",
ValidAudience = "account",
IssuerSigningKey = DummyKV.Key,
};
});
services.AddSwaggerGen(c=>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Account API",
Description = "Moula Coding Challenge - Account API"
});
c.AddSecurityDefinition("JWT", new OpenApiSecurityScheme
{
Description = "JWT token using Bearer scheme. Example: \"bearer {token}\"",
In = ParameterLocation.Header,
Scheme = "Bearer",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
c.OperationFilter<AuthRequirementFilter>();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Moula Coding Challenge");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
|
using UnityEngine;
namespace Khronos
{
public class ProceduralRingPartModule : PartModule
{
[KSPField] public Vector4 outlineColor = Color.red; //new Vector4(0, 0, 0.2f, 1);
[KSPField] public float outlineWidth = 0.05f;
[KSPField] public string radiusKey = "r";
[KSPField] public string widthKey = "w";
[KSPField] public string heightKey = "h";
[KSPField] public float speedMultiplier = 0.5f;
protected LineRenderer outline = null;
float alertTime = 0;
string alertText = null;
public override void OnStart(StartState state)
{
if (state == StartState.None) return;
else if ((state & StartState.Editor) == 0) drawMesh();
else enableForEditor();
}
public virtual void OnDestroy()
{
destroyOutline();
}
public virtual void destroyOutline()
{
if (!outline) return;
UnityEngine.Object.Destroy(outline.gameObject);
outline = null;
}
public virtual void enableForEditor()
{
}
public virtual void drawMesh()
{
}
protected string keyboardControls()
{
string s = "";
if (!string.IsNullOrEmpty(radiusKey)) s += "\nMouse over and hold '" + radiusKey + "' to adjust radius.";
if (!string.IsNullOrEmpty(widthKey)) s += "\nMouse over and hold '" + widthKey + "' to adjust the toroid width.";
if (!string.IsNullOrEmpty(heightKey)) s += "\nMouse over and hold '" + heightKey + "' to adjust the toroid height.";
return s;
}
protected LineRenderer makeLineRenderer(string name, Color color, float width, int vertexCount = 1)
{
var o = new GameObject(name);
o.transform.parent = part.transform;
o.transform.localPosition = Vector3.zero;
o.transform.localRotation = Quaternion.identity;
var r = o.AddComponent<LineRenderer>();
r.useWorldSpace = false;
r.material = new Material(Shader.Find("Particles/Additive"));
r.SetColors(color, color);
r.SetWidth(width, width);
r.SetVertexCount(vertexCount + 1);
return r;
}
// Logging / Alerting
protected void log(string message, params object[] list)
{
message = "[KPR] " + message;
if (list.Length > 0) message = string.Format(message, list);
Debug.Log(message);
}
protected void error(string message, params object[] list)
{
message = "[KPR] " + message;
if (list.Length > 0) message = string.Format(message, list);
Debug.LogError(message);
}
protected void alert(string message, float time)
{
alertTime = Time.time + time;
alertText = message;
}
public void OnGUI()
{
if (!HighLogic.LoadedSceneIsEditor) return;
if (Time.time < alertTime)
{
GUI.skin = HighLogic.Skin;
GUIStyle style = new GUIStyle("Label");
style.alignment = TextAnchor.MiddleCenter;
style.fontSize = 20;
style.normal.textColor = Color.black;
GUI.Label(new Rect(2, 2 + (Screen.height / 9), Screen.width, 50), alertText, style);
style.normal.textColor = Color.yellow;
GUI.Label(new Rect(0, Screen.height / 9, Screen.width, 50), alertText, style);
}
}
}
}
|
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 LoginForm.com.admin.userControl;
using LoginForm.com.supplier;
using LoginForm.com.product;
namespace LoginForm.com.admin {
public partial class AdminControllPage : Form {
string currentUserControl;
int adminID;
CashierControl cashier;
ProfitCalculationControl profit;
TransactionControl transaction;
//InventoryControl inventory;
SupplierControl supplier;
StockUserControl stock;
public AdminControllPage() {
InitializeComponent();
}
public AdminControllPage(string name) {
InitializeComponent();
this.currentUserControl = name;
}
public AdminControllPage(string name, int adminID)
: this(name) {
try {
// InitializeComponent();
//this.currentUserControl = name;
this.adminID = adminID;
cashier = new CashierControl(this, adminID);
cashier.Dock = DockStyle.Fill;
profit = new ProfitCalculationControl(this, adminID);
profit.Dock = DockStyle.Fill;
transaction = new TransactionControl(this, adminID);
transaction.Dock = DockStyle.Fill;
//inventory = new InventoryControl(this);
//inventory.Dock = DockStyle.Fill;
supplier = new SupplierControl(this, adminID);
supplier.Dock = DockStyle.Fill;
stock = new StockUserControl(this, adminID);
stock.Dock = DockStyle.Fill;
if (currentUserControl == "Cashier") {
mainPanel.Controls.Add(cashier);
cashier.BringToFront();
} else if (currentUserControl == "Profit") {
mainPanel.Controls.Add(profit);
profit.BringToFront();
} else if (currentUserControl == "Transaction") {
mainPanel.Controls.Add(transaction);
transaction.BringToFront();
}
//} else if (currentUserControl == "Inventory") {
// mainPanel.Controls.Add(inventory);
// inventory.BringToFront();
//}
else if (currentUserControl == "Supplier") {
mainPanel.Controls.Add(supplier);
supplier.BringToFront();
} else if (currentUserControl == "Stock") {
mainPanel.Controls.Add(stock);
stock.BringToFront();
}
} catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
private bool mouseDown;
private Point lastLocation;
private void Form_MouseDown(object sender, MouseEventArgs e) {
mouseDown = true;
lastLocation = e.Location;
}
private void Form_MouseMove(object sender, MouseEventArgs e) {
if (mouseDown) {
this.Location = new Point(
(this.Location.X - lastLocation.X) + e.X, (this.Location.Y - lastLocation.Y) + e.Y);
this.Update();
}
}
private void Form_MouseUp(object sender, MouseEventArgs e) {
mouseDown = false;
}
private void minimizeLabel_Click(object sender, EventArgs e) {
this.WindowState = FormWindowState.Minimized;
}
private void closeLabel_Click(object sender, EventArgs e) {
if (MessageBox.Show("Are You Sure?", "Close Window", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) {
Application.Exit();
}
}
private void AdminControllPage_Load(object sender, EventArgs e) {
}
}
}
|
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Constant of type `Vector2`. Inherits from `AtomBaseVariable<Vector2>`.
/// </summary>
[EditorIcon("atom-icon-teal")]
[CreateAssetMenu(menuName = "Unity Atoms/Constants/Vector2", fileName = "Vector2Constant")]
public sealed class Vector2Constant : AtomBaseVariable<Vector2> { }
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.