text
stringlengths
13
6.01M
//----------------------------------------------------------------------- // <copyright file="ControllerAttribute.cs" company="Aranea IT Ltd"> // Copyright (c) Aranea IT Ltd. All rights reserved. // </copyright> // <author>Szymon M Sasin</author> //----------------------------------------------------------------------- namespace IronSparrow.Core { using System; using System.Composition; using System.Web.Mvc; using IronSparrow.Contracts; /// <summary> /// Default Export attribute for controller /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true), MetadataAttribute] public class ControllerAttribute : ExportAttribute, IControllerMetadata { /// <summary> /// Initialises a new instance of the <see cref="ControllerAttribute"/> class. /// </summary> /// <param name="name">The name.</param> public ControllerAttribute(string name) : base(name.ToLower(), typeof(IController)) { this.Name = name; } /// <summary> /// Gets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string Name { get; private set; } } }
using System.Xml.Linq; using PlatformRacing3.Common.User; using PlatformRacing3.Web.Extensions; using PlatformRacing3.Web.Responses; using PlatformRacing3.Web.Responses.Procedures; namespace PlatformRacing3.Web.Controllers.DataAccess2.Procedures; public class CountMyFriendsProcedure : IProcedure { public async Task<IDataAccessDataResponse> GetResponseAsync(HttpContext httpContext, XDocument xml) { uint userId = httpContext.IsAuthenicatedPr3User(); if (userId > 0) { uint count = await UserManager.CountMyFriendsAsync(userId); return new DataAccessCountMyFriendsProcedureResponse(count); } else { return new DataAccessErrorResponse("You are not logged in!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using cloudfiles.contract; namespace cloudfiles.ironiocache.tests { [TestFixture] public class test_IronIOCache { private IronIOCache _sut; [SetUp] public void Setup() { var cre = IronIOCredentials.LoadFrom(@"..\..\..\..\..\unversioned\ironcache credentials.txt"); _sut = new IronIOCache("test", cre); } [Test] public void Integration() { var value = ""; _sut.Clear(); _sut.Add("newkey", "hello"); Assert.AreEqual("hello", _sut.Get("newkey")); Assert.IsTrue(_sut.TryGet("newkey", out value)); Assert.AreEqual("hello", value); _sut.Remove("newkey"); Assert.Throws<KeyValueStoreException>(() => _sut.Get("newkey")); Assert.IsFalse(_sut.TryGet("newkey", out value)); _sut.ReplaceOrAdd("newkey2", "world"); Assert.AreEqual("world", _sut.Get("newkey2")); _sut.ReplaceOrAdd("newkey2", "quick brown fox"); Assert.AreEqual("quick brown fox", _sut.Get("newkey2")); Assert.AreEqual(1, _sut.Increment("newcounter", 1)); Assert.AreEqual(10, _sut.Increment("newcounter", 9)); } } }
namespace ServiceDesk.Api.Systems.DirectorySystem.Dtos.Software { public class SoftwareCreateDto { public string Title { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace bntu_10702117_Course_project_Zayicev { class GeometryPoint { public int Count { get; set; } public double X { get; set; } public double Y { get; set; } public double Z { get; set; } public GeometryPoint(double x, double y, double z) { X = x; Y = y; Z = z; } public GeometryPoint(double[] xyz) { X = xyz[0]; Y = xyz[1]; Z = xyz[2]; } } }
using UnityEngine; using UnityEngine.Audio; public class WavesSpawner : MonoBehaviour { public GameObject wavesPrefab; public GameObject endScreen; public AudioClip[] audios; public AudioMixerGroup[] mixerGroups; public Color[] colors; private MoveForward playerForward; private int current = 0; private void Start() { playerForward = GameObject.FindGameObjectWithTag("MovingElements").GetComponent<MoveForward>(); } private void Update() { if (current == 0 && playerForward.x > 100) AddNextWave(); if (current == 1 && playerForward.x > 300) AddNextWave(); if (current == 2 && playerForward.x > 500) AddNextWave(); if (current == 3 && playerForward.x > 700) AddNextWave(); if (current > 0 && playerForward.x > 1100) { endScreen.GetComponent<FadeIn>().StartFadeIn(); current = -1; } } void AddNextWave() { if (current < audios.Length) { AddWave(current); current++; } } public void AddWave(int waveNumber) { if (audios[waveNumber] != null) { GameObject friendlyWave = Instantiate(wavesPrefab); friendlyWave.GetComponentInChildren<FriendlyWave>().visuals.SetColor(colors[waveNumber]); friendlyWave.GetComponentInChildren<FriendlyWave>().audioSource.clip = audios[waveNumber]; friendlyWave.GetComponentInChildren<FriendlyWave>().audioSource.outputAudioMixerGroup = mixerGroups[waveNumber]; friendlyWave.GetComponentInChildren<FriendlyWave>().audioSource.Play(); friendlyWave.transform.position = new Vector3(playerForward.x - 20, Random.Range(-9, 9), -2); } } public Color GetCurrentColor() { return colors[current]; } }
namespace GetLabourManager.Migrations { using System; using System.Data.Entity.Migrations; public partial class CostSheet_migration : DbMigration { public override void Up() { CreateTable( "dbo.CostSheets", c => new { Id = c.Int(nullable: false, identity: true), DatePrepared = c.DateTime(nullable: false), CostSheetNumber = c.String(nullable: false, maxLength: 25), RequestHeader = c.Int(nullable: false), PreparedBy = c.Int(nullable: false), Note = c.String(), Status = c.String(maxLength: 15), Client = c.Int(nullable: false), }).Index(x=>x.Id) .PrimaryKey(t => t.Id); CreateTable( "dbo.CostSheetItems", c => new { Id = c.Int(nullable: false, identity: true), RaisedOn = c.DateTime(nullable: false), StaffCode = c.String(maxLength: 20), FullName = c.String(maxLength: 150), Gang = c.String(maxLength: 20), GroupName = c.String(maxLength: 20), Container = c.Int(nullable: false), HourseWorked = c.Double(), CostSheetId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.CostSheets", t => t.CostSheetId) .Index(t => t.CostSheetId); } public override void Down() { DropForeignKey("dbo.CostSheetItems", "CostSheetId", "dbo.CostSheets"); DropIndex("dbo.CostSheetItems", new[] { "CostSheetId" }); DropTable("dbo.CostSheetItems"); DropTable("dbo.CostSheets"); } } }
/* * Copyright 2014 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using KaVE.Commons.Model.Events; using KaVE.Commons.Model.Events.CompletionEvents; using KaVE.Commons.Model.Events.VisualStudio; using KaVE.Commons.Model.Naming; using KaVE.Commons.Model.SSTs.Impl; using KaVE.VS.FeedbackGenerator.SessionManager.Presentation; using NUnit.Framework; namespace KaVE.VS.FeedbackGenerator.Tests.SessionManager.Presentation { internal class IDEEventDetailsToJsonConverterTest { [Test] public void ShouldConvertActionEventDetailsToXaml() { var actionEvent = new WindowEvent { Window = Names.Window("w MyWindow"), Action = WindowAction.Create }; var expected = string.Join( Environment.NewLine, " \"Window\": \"w MyWindow\"", " \"Action\": \"Create\""); var actual = actionEvent.GetDetailsAsJson(); Assert.AreEqual(expected, actual); } [Test] public void ShouldConvertCompletionEventWhileHidingProperties() { var completionEvent = new CompletionEvent { Context2 = new Context {SST = new SST {EnclosingType = Names.Type("TestClass,TestProject")}}, ProposalCollection = { new Proposal {Name = Names.Field("[FieldType,P] [TestClass,P].SomeField")}, new Proposal {Name = Names.Event("[EventType`1[[T -> EventArgsType,P]],P] [DeclaringType,P].E")}, new Proposal {Name = Names.Method("[ReturnType,P] [DeclaringType,P].M([ParameterType,P] p)")} }, Selections = { new ProposalSelection { Proposal = new Proposal {Name = Names.Field("[FieldType,P] [TestClass,P].SomeField")}, SelectedAfter = TimeSpan.FromSeconds(1) }, new ProposalSelection { Proposal = new Proposal { Name = Names.Event("[EventType`1[[T -> EventArgsType,P]],P] [DeclaringType,P].E") }, SelectedAfter = TimeSpan.FromSeconds(2) }, new ProposalSelection { Proposal = new Proposal { Name = Names.Method("[ReturnType,P] [DeclaringType,P].M([ParameterType,P] p)") }, SelectedAfter = TimeSpan.FromSeconds(3) } }, TerminatedBy = EventTrigger.Typing, TerminatedState = TerminationState.Cancelled, ProposalCount = 1 }; var expected = string.Join( Environment.NewLine, " \"TerminatedBy\": \"Typing\"", " \"TerminatedState\": \"Cancelled\"", " \"ProposalCount\": 1"); var actual = completionEvent.GetDetailsAsJson(); Assert.AreEqual(expected, actual); } [Test] public void ShouldFormatEditEventDetailsWhileHidingContext() { var editEvent = new EditEvent { Context2 = new Context {SST = new SST {EnclosingType = Names.Type("TestClass,TestProject")}}, NumberOfChanges = 2, SizeOfChanges = 20 }; var expected = String.Join( Environment.NewLine, " \"NumberOfChanges\": 2", " \"SizeOfChanges\": 20"); var actual = editEvent.GetDetailsAsJson(); Assert.AreEqual(expected, actual); } [Test] public void ShouldNotIncludeIDEEventPropertiesInDetails() { var actionEvent = new CommandEvent { ActiveDocument = Names.Document("d Doc"), ActiveWindow = Names.Window("w Window"), IDESessionUUID = "UUID", TerminatedAt = DateTime.Now, TriggeredAt = DateTime.Now, TriggeredBy = EventTrigger.Click }; const string expected = ""; var actual = actionEvent.GetDetailsAsJson(); Assert.AreEqual(expected, actual); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Memmberships.Extensions { public static class ReflectionExtensions //static because it is pre requisite of reflection method { public static string GetPropertyValue <T>(this T item, string propertyName) { return item.GetType().GetProperty(propertyName).GetValue(item, null).ToString(); } } }
namespace EntityFrameworkCoreExample.Models { public class Character { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public bool Gender { get; set; } public int Age { get; set; } public int StoryId { get; set; } public virtual Story Story { get; set; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace WallPaperChangerV2 { public class GenerateWallpaper { public static String OUTFILE = "Wallpaper.jpg"; Bitmap wallBitmap; private Graphics wallPaper; private string files; private int numFiles; private ScreenFetcher screens; private List<string> currentImages; private int counter; private int outputFileNumber; bool isRandom; /// <summary> /// Constructor /// </summary> public GenerateWallpaper( ScreenFetcher screens, string files, bool isRandom ) { this.screens = screens; this.files = files; this.isRandom = isRandom; counter = 0; outputFileNumber = 0; } /// <summary> /// Creates the image that will be displayed /// </summary> public string generateImage() { screens.RefreshScreens(); // Clear the file that is stored on disk and set as wallpaper. if ( File.Exists( outputFileNumber + ".jpg" ) ) { File.Delete( ( outputFileNumber + ".jpg" ) ); } // Dispose of the bitmap thats used to make the file. if ( wallBitmap != null ) { wallBitmap.Dispose(); } // Clean the graphics class. if ( wallPaper != null ) { wallPaper.Dispose(); } // Reset the above items. wallBitmap = new Bitmap( screens.Size.Width, screens.Size.Height ); wallPaper = Graphics.FromImage( wallBitmap ); // Get a group of files that will be used for the first runthough. if ( currentImages == null ) { currentImages = new List<string>(); for ( int i = 0; i < screens.Count; i++ ) { currentImages.Add( getFile() ); Thread.Sleep( 100 ); } counter++; } // Remove current image for current screen and regenerate the bitmap. for ( int i = 0; i < screens.Count; i++ ) { // Clear storage for selected screen and get random image to use. if ( counter % screens.Count == i ) { currentImages.RemoveAt( i ); string nextImage = getFile(); while ( currentImages.Contains( nextImage ) ) { nextImage = getFile(); } currentImages.Insert( i, nextImage ); } // Load the image Image loadedImage = Image.FromFile( currentImages.ElementAt( i ) ); Bitmap currentBitmap = new Bitmap( screens.ElementAt( i ).ScreenSize.Width, screens.ElementAt( i ).ScreenSize.Height ); // Get the image size and height that it should be scaled too. // TODO: Split into seperate method? // Remark: Its also done in resize image. int bitmapHeight; int bitmapWidth; if ( screens.ElementAt( i ).ScreenSize.Height < screens.ElementAt( i ).ScreenSize.Width ) { bitmapWidth = screens.ElementAt( i ).ScreenSize.Height * loadedImage.Width / loadedImage.Height; bitmapHeight = screens.ElementAt( i ).ScreenSize.Height; } else { bitmapWidth = screens.ElementAt( i ).ScreenSize.Width; bitmapHeight = screens.ElementAt( i ).ScreenSize.Width * loadedImage.Height / loadedImage.Width; } // Resize the image to fit the screen. ResizeImage( screens.ElementAt( i ).ScreenSize, loadedImage, currentBitmap ); // Draw the image. Point point = new Point( screens.ElementAt( i ).BitmapLocation.X + ( screens.ElementAt( i ).ScreenSize.Width - bitmapWidth ) / 2, screens.ElementAt( i ).BitmapLocation.Y + ( screens.ElementAt( i ).ScreenSize.Height - bitmapHeight ) / 2 ); wallPaper.DrawImage( currentBitmap, point ); // Clean up. loadedImage.Dispose(); currentBitmap.Dispose(); } // Final clean up counter++; outputFileNumber = ++outputFileNumber % 5; wallBitmap.Save( ( outputFileNumber + ".jpg" ) ); // The file name that was written. return ( outputFileNumber + ".jpg" ); } /// <summary> /// Gets a list of files. /// </summary> private string getFile() { // Get a list of files. if ( isRandom ) { FileInfo[] allFiles = GetFiles(); return allFiles[getRandomNumber()].FullName; } else { FileInfo[] allFiles = GetFiles(); return allFiles[counter % allFiles.Count()].FullName; } } /// <summary> /// Resize image to fit in screen. /// </summary> private void ResizeImage( Size size, Image tempImage, Bitmap currentBitmap ) { // Use graphics and scale image to fit given size. using ( Graphics gr = Graphics.FromImage( currentBitmap ) ) { gr.SmoothingMode = SmoothingMode.HighQuality; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; if( size.Height < size.Width && tempImage.Height > tempImage.Width ) { gr.DrawImage( tempImage, new Rectangle( 0, 0, size.Height * tempImage.Height / tempImage.Width, size.Height ) ); } else if ( size.Height < size.Width && tempImage.Height < tempImage.Width ) { gr.DrawImage( tempImage, new Rectangle( 0, 0, size.Height * tempImage.Width / tempImage.Height, size.Height ) ); } else if ( size.Height > size.Width && tempImage.Height > tempImage.Width ) { gr.DrawImage( tempImage, new Rectangle( 0, 0, size.Width, size.Width * tempImage.Height / tempImage.Width ) ); } else if ( size.Height > size.Width && tempImage.Height < tempImage.Width ) { gr.DrawImage( tempImage, new Rectangle( 0, 0, size.Width, size.Width * tempImage.Width / tempImage.Height ) ); } } } /// <summary> /// Get all the files that will be used. /// </summary> private FileInfo[] GetFiles() { DirectoryInfo folder = new DirectoryInfo( this.files + "\\" ); FileInfo[] files = folder.GetFiles(); Array.Sort( files, ( f1, f2 ) => f1.Name.CompareTo( f2.Name ) ); numFiles = folder.GetFiles().Count(); return files; } /// <summary> /// Get a random number bounded by the number of files. /// </summary> private int getRandomNumber() { return new Random().Next( numFiles ); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; public class ClanSheetUI : MonoBehaviour { public ClanSheet ClanSheet; public GameObject RemoveButton; public Text PlayerNameText; public Player Player; // Use this for initialization }
using System; using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; using System.Text; namespace System.Data.Linq.Provider { using System.Data.Linq.Mapping; internal interface IDataServices { DataContext Context { get; } MetaModel Model { get; } IDeferredSourceFactory GetDeferredSourceFactory(MetaDataMember member); object GetCachedObject(Expression query); bool IsCachedObject(MetaType type, object instance); object InsertLookupCachedObject(MetaType type, object instance); void OnEntityMaterialized(MetaType type, object instance); } internal interface IDeferredSourceFactory { IEnumerable CreateDeferredSource(object instance); IEnumerable CreateDeferredSource(object[] keyValues); } }
using System; using System.Collections.Generic; using System.ServiceModel; using KT.DTOs.Objects; namespace KT.ServiceInterfaces { [ServiceContract] public interface IKtSubcategoriesService { [OperationContract] SubcategoryDto[] GetAll(); [OperationContract] void Insert(SubcategoryDto subCat); [OperationContract] SubcategoryDto[] GetByCategory(Guid catId); [OperationContract] SubcategoryDto GetById(Guid subCatId); [OperationContract] Guid Save(string name, Guid catId, Guid? subcatId = null); [OperationContract] void Delete(Guid id); [OperationContract] int GetCountByCategory(Guid id); } }
using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using System; using System.IO; using System.Threading; using System.Net; using System.Threading.Tasks; namespace DevHawk.WazStorageExtensions { public static class BlobExtensions { public static string TryAcquireLease(this ICloudBlob blob, TimeSpan? leaseTime = null, string proposedLeaseId = null, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { try { return blob.AcquireLease(leaseTime, proposedLeaseId, accessCondition, options, operationContext); } catch (StorageException ex) { if (ex.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict) return null; else throw; } } public static Task SetMetadataAsync(this ICloudBlob blob, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { return Task.Factory.FromAsync( (cb, ob) => blob.BeginSetMetadata(accessCondition, options, operationContext, cb, ob), blob.EndSetMetadata, null); } public static Task FetchAttributesAsync(this ICloudBlob blob, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { return Task.Factory.FromAsync( (cb, ob) => blob.BeginFetchAttributes(accessCondition, options, operationContext, cb, ob), blob.EndFetchAttributes, null); } public static bool TryRenewLease(this ICloudBlob blob, AccessCondition accessCondition, BlobRequestOptions options = null, OperationContext operationContext = null) { try { blob.RenewLease(accessCondition, options, operationContext); return true; } catch { return false; } } public static Task<string> AquireLeaseAsync(this ICloudBlob blob, TimeSpan? leaseTime = null, string proposedLeaseId = null, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { return Task.Factory.FromAsync<string>( (cb, ob) => blob.BeginAcquireLease(leaseTime, proposedLeaseId, accessCondition, options, operationContext, cb, ob), blob.EndAcquireLease, null); } public static Task<string> TryAquireLeaseAsync(this ICloudBlob blob, TimeSpan? leaseTime = null, string proposedLeaseId = null, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { var tcs = new TaskCompletionSource<string>(); blob.AquireLeaseAsync(leaseTime, proposedLeaseId, accessCondition, options, operationContext) .ContinueWith(t => { if (!t.IsFaulted) { tcs.SetResult(t.Result); } else { if (t.Exception.InnerExceptions.Count > 1) tcs.TrySetException(t.Exception); else { var ex = t.Exception.InnerExceptions[0] as StorageException; if (ex != null && ex.RequestInformation.HttpStatusCode == (int)HttpStatusCode.Conflict) { tcs.SetResult(null); } else { tcs.TrySetException(t.Exception.InnerExceptions[0]); } } } }); return tcs.Task; } public static Task<bool> CreateIfNotExistsAsync(this CloudBlobContainer container) { return Task.Factory.FromAsync<bool>( (cb, ob) => container.BeginCreateIfNotExists(cb, ob), container.EndCreateIfNotExists, null); } public static Task UploadFromStreamAsync(this ICloudBlob blockBlob, System.IO.Stream stream, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { return Task.Factory.FromAsync( (cb, ob) => blockBlob.BeginUploadFromStream(stream, accessCondition, options, operationContext, cb, ob), blockBlob.EndUploadFromStream, null); } public static Task DownloadToStreamAsync(this ICloudBlob blob, System.IO.Stream stream, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { return Task.Factory.FromAsync( (cb, ob) => blob.BeginDownloadToStream(stream, accessCondition, options, operationContext, cb, ob), blob.EndDownloadToStream, null); } public static Task<bool> ExistsAsync(this ICloudBlob blob, BlobRequestOptions options = null, OperationContext operationContext = null) { return Task.Factory.FromAsync<bool>( (cb, ob) => blob.BeginExists(options, operationContext, cb, ob), blob.EndExists, null); } } }
using DesignPattern.Models; using DesignPattern.RepositoryPattern; using DesignPattern.StrategyPattern; using DesignPattern.UnitOfWorkPattern; using System; using System.Linq; namespace DesignPattern { class Program { static void Main(string[] args) { var context = new Context(new CarStrategy()); context.Run(); context.Strategy = new MotoStrategy(); context.Run(); context.Strategy = new BicycleStrategy(); context.Run(); } } }
 using log4net; using log4net.Config; using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Threading; using UrTBot.Properties; using UrTLibrary.Server; namespace UrTBot { internal class Program { static ILog log = LogManager.GetLogger("Main"); private static void Main(string[] args) { XmlConfigurator.Configure(); Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); string gameDir = Path.Combine(Settings.Default.BasePath, Settings.Default.Game); string logFile = Path.Combine(gameDir, Settings.Default.LogFile); GameServer gameServer = new GameServer(Settings.Default.Address, Settings.Default.Port, Settings.Default.RConPassword, gameDir, logFile, Settings.Default.UJKey, Settings.Default.GroupFile, Settings.Default.ClientFile, Settings.Default.CommandFile); gameServer.StartReadingLogs(); Console.WriteLine("Press <ENTER> to exit.."); Console.WriteLine(); log.Info("Saying hello to server.."); gameServer.QueryManager.Say("Bot activated."); Console.Read(); gameServer.StopReadingLogs(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; using System.Data.SqlClient; public class DataBaseManger : MonoBehaviour { public static SqlConnection Connection; public static string ConString = //@"Data Source=ADAMS\SQLEXPRESS; //Initial Catalog=SomeCity; //Integrated Security=True"; @"Server=ADAMS\SQLEXPRESS; Database=SomeCity; Integrated Security=True"; void Start() { //Connection = new SqlConnection(ConString); //Connection.Open(); //var q = "select * from OnGround"; //var c = new SqlCommand(q, Connection); //var reader = c.ExecuteReader(); //reader.Read(); //Debug.Log(reader["ZPoz"]); //reader.Close(); //Connection.Close(); } public static void LoadAll() { } }
/* ********************************************** * 版 权:亿水泰科(EWater) * 创建人:zhujun * 日 期:2019/2/28 16:18:40 * 描 述:SimpleCRUD * *********************************************/ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CSharp.RuntimeBinder; namespace Dapper { /// <summary> /// Main class for Dapper.SimpleCRUD extensions /// </summary> public static partial class SimpleCRUD { /// <summary> /// <para>By default queries the table matching the class name</para> /// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para> /// <para>whereConditions is an anonymous type to filter the results ex: new {Category = 1, SubCategory=2}</para> /// <para>Supports transaction and command timeout</para> /// <para>Returns a list of entities that match where conditions</para> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="connection"></param> /// <param name="whereConditions"></param> /// <param name="transaction"></param> /// <param name="commandTimeout"></param> /// <returns>Gets a list of entities with optional exact match where conditions</returns> public static IEnumerable<T> GetList<T>(this IDbConnection connection, object whereConditions, IDbTransaction transaction = null, int? commandTimeout = null) { var currenttype = typeof(T); var idProps = GetIdProperties(currenttype).ToList(); if (!idProps.Any()) throw new ArgumentException("Entity must have at least one [Key] property"); var name = GetTableName(currenttype); var sb = new StringBuilder(); var whereprops = GetAllProperties(whereConditions).ToArray(); sb.Append("Select "); //create a new empty instance of the type to get the base properties BuildSelect(sb, GetScaffoldableProperties<T>().ToArray()); sb.AppendFormat(" from {0}", name); if (whereprops.Any()) { sb.Append(" where "); BuildWhere<T>(sb, whereprops, whereConditions); } if (Debugger.IsAttached) Trace.WriteLine(String.Format("GetList<{0}>: {1}", currenttype, sb)); return connection.Query<T>(sb.ToString(), whereConditions, transaction, true, commandTimeout); } /// <summary> /// <para>By default queries the table matching the class name</para> /// <para>-Table name can be overridden by adding an attribute on your class [Table("YourTableName")]</para> /// <para>conditions is an SQL where clause and/or order by clause ex: "where name='bob'" or "where age>=@Age"</para> /// <para>parameters is an anonymous type to pass in named parameter values: new { Age = 15 }</para> /// <para>Supports transaction and command timeout</para> /// <para>Returns a list of entities that match where conditions</para> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="connection"></param> /// <param name="conditions"></param> /// <param name="parameters"></param> /// <param name="transaction"></param> /// <param name="commandTimeout"></param> /// <returns>Gets a list of entities with optional SQL where conditions</returns> public static IEnumerable<T> GetList<T>(this IDbConnection connection, string conditions, object parameters = null, IDbTransaction transaction = null, int? commandTimeout = null) { var currenttype = typeof(T); var idProps = GetIdProperties(currenttype).ToList(); if (!idProps.Any()) throw new ArgumentException("Entity must have at least one [Key] property"); var name = GetTableName(currenttype); var sb = new StringBuilder(); sb.Append("Select "); //create a new empty instance of the type to get the base properties BuildSelect(sb, GetScaffoldableProperties<T>().ToArray()); sb.AppendFormat(" from {0}", name); sb.Append(" " + conditions); if (Debugger.IsAttached) Trace.WriteLine(String.Format("GetList<{0}>: {1}", currenttype, sb)); return connection.Query<T>(sb.ToString(), parameters, transaction, true, commandTimeout); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ERP_Palmeiras_LA.Models; using ERP_Palmeiras_LA.Models.Facade; namespace ERP_Palmeiras_LA.Controllers { public class TestesController : BaseController { // // GET: /Testes/ LogisticaAbastecimento facade = LogisticaAbastecimento.GetInstance(); public ActionResult CriarCenario() { // verifica se o cenário ja foi criado.. IEnumerable<Fabricante> ff1 = facade.BuscarFabricantes(); if (ff1 == null || ff1.Count<Fabricante>() > 0) return RedirectToAction("Welcome", "Home"); Fabricante f1 = new Fabricante(); f1.Agencia = "222-2"; f1.Banco = 210; f1.CNPJ = "111.111.111-11"; f1.ContaCorrente = "1010-1"; f1.Nome = "Jonas Equipamentos"; facade.CriarFabricante(f1); Fabricante f2 = new Fabricante(); f2.Agencia = "333-3"; f2.Banco = 210; f2.CNPJ = "333.333.333-33"; f2.ContaCorrente = "2020-2"; f2.Nome = "Jonas Materiais"; facade.CriarFabricante(f2); Material m1 = new Material(); m1.Codigo = "M-001"; m1.Descricao = "Luva Cirúrgica de Látex"; m1.Nome = "Luva Cirúrgica"; m1.QuantidadeEstoque = 100; m1.FabricanteId = f2.Id; facade.InserirMaterial(m1); Material m2 = new Material(); m2.Codigo = "M-002"; m2.Descricao = "Pinça Descartável"; m2.Nome = "Pinça cirúrgica descartável de alumínio"; m2.QuantidadeEstoque = 50; m2.FabricanteId = f2.Id; facade.InserirMaterial(m2); Equipamento e1 = new Equipamento(); e1.Nome = "Máquina de Raio-X"; e1.NumeroSerie = "E-001"; e1.Descricao = "Máquina de Raio-X"; e1.FabricanteId = f1.Id; facade.CriarEquipamento(e1); Equipamento e2 = new Equipamento(); e2.Nome = "Máquina de Ultrassom"; e2.NumeroSerie = "E-002"; e2.Descricao = "Máquina de Ultrassom"; e2.FabricanteId = f1.Id; facade.CriarEquipamento(e2); return RedirectToAction("Welcome", "Home"); } } }
namespace UserVoiceSystem.Services.Data.Common { using System.Linq; using UserVoiceSystem.Data.Models; public interface ICommentsService { IQueryable<Comment> GetAll(); Comment GetById(string id); void Create(Comment comment); void Update(Comment comment); void Delete(Comment comment); } }
namespace RangeExceptions { using System; class Program { static void Main() { const int startRangeInt = 1; const int endRangeInt = 100; DateTime startRangeDate = DateTime.Parse("1.1.1980"); DateTime endRangeDate = DateTime.Parse("31.12.2013"); int[] test = new int[] { 92, 102, 0 }; for (int index = 0; index < test.Length; index++) { try { if (test[index] < startRangeInt || test[index] > endRangeInt) throw new InvalidRangeException<int>(test[index]); Console.WriteLine(test[index]); } catch (InvalidRangeException<int> ex) { Console.WriteLine(ex.Message); } } var testDate = new DateTime[] { DateTime.Parse("20.12.2014"), DateTime.Parse("21.03.2011") }; for (int index = 0; index < testDate.Length; index++) { try { if (testDate[index] < startRangeDate || testDate[index] > endRangeDate) throw new InvalidRangeException<DateTime>(testDate[index]); Console.WriteLine("{0:dd.MM.yyyy}", testDate[index]); } catch (InvalidRangeException<DateTime> ex) { Console.WriteLine(ex.Message); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPS.MFiles.Common { public class Content { public static readonly string SPFileTypes = "SPFileTypes"; public static readonly string SPFileSizes = "SPFileSizes"; public static readonly string SPFileTypesActive = "SPFileTypesActive"; } }
using Core.Entities; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace Core.DataAccess.EntityFramework { public class EfEntityRepositoryBase<TEntity,TContext>: IEntityRepository<TEntity> where TEntity: class, IEntity, new() where TContext : DbContext,new() { public async Task<TEntity> GetAsync(Expression<Func<TEntity, bool>> filter) { using (TContext context = new TContext()) { return await context.Set<TEntity>().SingleOrDefaultAsync(filter); } } public async Task<List<TEntity>> GetAllAsync(Expression<Func<TEntity, bool>> filter = null) { using (TContext context = new TContext()) { return filter == null ? await context.Set<TEntity>().ToListAsync() : await context.Set<TEntity>().Where(filter).ToListAsync(); } } public List<TEntity> GetAll(Expression<Func<TEntity, bool>> filter = null) { using (TContext context = new TContext()) { return filter == null ? context.Set<TEntity>().ToList() : context.Set<TEntity>().Where(filter).ToList(); } } public TEntity Get(Expression<Func<TEntity, bool>> filter) { using (TContext context = new TContext()) { return context.Set<TEntity>().SingleOrDefault(filter); } } public void Add(TEntity entity) { using (TContext context = new TContext()) { var addedEntity = context.Entry(entity); addedEntity.State = EntityState.Added; context.SaveChangesAsync(); } } public async Task AddAsync(TEntity entity) { using (TContext context = new TContext()) { var addedEntity = context.Entry(entity); addedEntity.State = EntityState.Added; await context.SaveChangesAsync(); } } public async Task DeleteAsync(TEntity entity) { using (TContext context = new TContext()) { var deletedEntity = context.Entry(entity); deletedEntity.State = EntityState.Deleted; await context.SaveChangesAsync(); } } public async Task MultiAddAsync(TEntity[] entities) { using (TContext context = new TContext()) { foreach (var entity in entities) { var multiAddedEntity = context.Entry(entity); multiAddedEntity.State = EntityState.Added; await context.SaveChangesAsync(); } } } public async Task UpdateAsync(TEntity entity) { using (TContext context = new TContext()) { var updatedEntity = context.Entry(entity); updatedEntity.State = EntityState.Modified; await context.SaveChangesAsync(); } } } }
using System; using System.Collections.Generic; using System.Text; namespace Reserva.Domain.Command.Result { public class ReservaCommadResult { public string Filial { get; set; } public string NomeUsuario { get; set; } public string NomeSala { get; set; } public int ReservaId { get; set; } public DateTime DataInicio { get; set; } public string HoraInicio { get; set; } public DateTime DataFim { get; set; } public string HoraFim { get; set; } public bool Café { get; set; } public int QuantidadePessoa { get; set; } public int SalaId { get; set; } } }
/* * Copyright 2014 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using JetBrains.Application; using KaVE.RS.Commons; namespace KaVE.VS.FeedbackGenerator.Utils.Logging { [ShellComponent] public class IDEEventLogFileManager : LogFileManager { public const string ProjectName = "KaVE"; /// <summary> /// Usually something like "C:\Users\%USERNAME%\AppData\Roaming\" /// </summary> public static readonly string AppDataPath = Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData); /// <summary> /// Usually something like "C:\Users\%USERNAME%\AppData\Local\" /// </summary> public static readonly string LocalAppDataPath = Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData); public static readonly string EventLogsScope = typeof(IDEEventLogFileManager).Assembly.GetName().Name; /// <summary> /// E.g., "C:\Users\%USERNAME%\AppData\Local\KaVE\KaVE.VS.FeedbackGenerator\%VARIANT%\" /// </summary> public static readonly string EventLogsPath = Path.Combine(LocalAppDataPath, ProjectName, EventLogsScope); public IDEEventLogFileManager(FeedBaGVersionUtil versionUtil) : base(Path.Combine(EventLogsPath, versionUtil.GetVariant().ToString())) { } } }
using System; namespace Micro.Net.Feature.Deduplication { public class Class1 { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallSpawner : MonoBehaviour { [SerializeField] private GameObject _bowlingBall; [SerializeField] private List<Material> _materials = new List<Material>(); [SerializeField] private int _spawnIntervalMin = 1; [SerializeField] private int _spawnIntervalMax = 7; private void Start() { StartCoroutine(SpawnBall()); } private IEnumerator SpawnBall() { yield return new WaitForSeconds(Random.Range(_spawnIntervalMin, _spawnIntervalMax)); Instantiate(_bowlingBall, transform.position, Quaternion.identity); StartCoroutine(SpawnBall()); } }
using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace BattleShip { class Battlefield { private int x = 0; private int y = 0; private bool horizontailVertical = true; private List<Coordinates> tempCoor = new List<Coordinates>(); Ships patrolBoat = new Ships("Patrol Boat", 3, true, "p"); string[,] battlefield = new string[10, 10]; bool[,] shipPlacement = new bool[10, 10]; public Battlefield() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { battlefield[i, j] = " "; shipPlacement[i, j] = false; } } } public void controlShipPlacement(ConsoleKey consoleKey) { tempCoor.Clear(); for (int i = 0; i < patrolBoat.ShipLength; i++) { if (x >= 0 && y >= 0 && x + patrolBoat.ShipLength < 10 && y + patrolBoat.ShipLength < 10) { if (horizontailVertical == true) {tempCoor.Add(new Coordinates { X = x + i, Y = y });} else if (horizontailVertical == false) {tempCoor.Add(new Coordinates { X = x, Y = y + i });} } else { if (x < 0) { x = 0; } else if (y < 0) { y = 0; } else if (x > 10) { y = 9; } else if (y > 10) { y = 9; } } } switch (consoleKey) { case ConsoleKey.LeftArrow: x = x - 1; break; case ConsoleKey.UpArrow: y = y - 1; break; case ConsoleKey.RightArrow: x = x + 1; break; case ConsoleKey.DownArrow: y = y + 1; break; case ConsoleKey.R: if (horizontailVertical == true) { horizontailVertical = false; } else if (horizontailVertical == false) { horizontailVertical = true; } break; default: break; } RotatedHorizontal(); } public void RotatedHorizontal() { if (horizontailVertical == true) { if (x + patrolBoat.ShipLength < 10 && x >= 0 && y < 10 && y >= 0) { foreach (Coordinates Co in tempCoor) { battlefield[Co.Y, Co.X] = " "; } for (int i = 0; i < patrolBoat.ShipLength; i++) { battlefield[y, x + i] = patrolBoat.ShipIndicator; } } } else if (horizontailVertical == false) { if (x < 10 && x >= 0 && y + patrolBoat.ShipLength < 10 && y >= 0) { foreach (Coordinates Co in tempCoor) { battlefield[Co.Y, Co.X] = " "; } for (int i = 0; i < patrolBoat.ShipLength; i++) { battlefield[y + i, x] = patrolBoat.ShipIndicator; } } } } public override string ToString() { return "----------------------------------------\n" + "| " + battlefield[0, 0] + " | " + battlefield[0, 1] + " | " + battlefield[0, 2] + " | " + battlefield[0, 3] + " | " + battlefield[0, 4] + " | " + battlefield[0, 5] + " | " + battlefield[0, 6] + " | " + battlefield[0, 7] + " | " + battlefield[0, 8] + " | " + battlefield[0, 9] + " |\n" + "----------------------------------------\n" + "| " + battlefield[1, 0] + " | " + battlefield[1, 1] + " | " + battlefield[1, 2] + " | " + battlefield[1, 3] + " | " + battlefield[1, 4] + " | " + battlefield[1, 5] + " | " + battlefield[1, 6] + " | " + battlefield[1, 7] + " | " + battlefield[1, 8] + " | " + battlefield[1, 9] + " |\n" + "----------------------------------------\n" + "| " + battlefield[2, 0] + " | " + battlefield[2, 1] + " | " + battlefield[2, 2] + " | " + battlefield[2, 3] + " | " + battlefield[2, 4] + " | " + battlefield[2, 5] + " | " + battlefield[2, 6] + " | " + battlefield[2, 7] + " | " + battlefield[2, 8] + " | " + battlefield[2, 9] + " |\n" + "----------------------------------------\n" + "| " + battlefield[3, 0] + " | " + battlefield[3, 1] + " | " + battlefield[3, 2] + " | " + battlefield[3, 3] + " | " + battlefield[3, 4] + " | " + battlefield[3, 5] + " | " + battlefield[3, 6] + " | " + battlefield[3, 7] + " | " + battlefield[3, 8] + " | " + battlefield[3, 9] + " |\n" + "----------------------------------------\n" + "| " + battlefield[4, 0] + " | " + battlefield[4, 1] + " | " + battlefield[4, 2] + " | " + battlefield[4, 3] + " | " + battlefield[4, 4] + " | " + battlefield[4, 5] + " | " + battlefield[4, 6] + " | " + battlefield[4, 7] + " | " + battlefield[4, 8] + " | " + battlefield[4, 9] + " |\n" + "----------------------------------------\n" + "| " + battlefield[5, 0] + " | " + battlefield[5, 1] + " | " + battlefield[5, 2] + " | " + battlefield[5, 3] + " | " + battlefield[5, 4] + " | " + battlefield[5, 5] + " | " + battlefield[5, 6] + " | " + battlefield[5, 7] + " | " + battlefield[5, 8] + " | " + battlefield[5, 9] + " |\n" + "----------------------------------------\n" + "| " + battlefield[6, 0] + " | " + battlefield[6, 1] + " | " + battlefield[6, 2] + " | " + battlefield[6, 3] + " | " + battlefield[6, 4] + " | " + battlefield[6, 5] + " | " + battlefield[6, 6] + " | " + battlefield[6, 7] + " | " + battlefield[6, 8] + " | " + battlefield[6, 9] + " |\n" + "----------------------------------------\n" + "| " + battlefield[7, 0] + " | " + battlefield[7, 1] + " | " + battlefield[7, 2] + " | " + battlefield[7, 3] + " | " + battlefield[7, 4] + " | " + battlefield[7, 5] + " | " + battlefield[7, 6] + " | " + battlefield[7, 7] + " | " + battlefield[7, 8] + " | " + battlefield[7, 9] + " |\n" + "----------------------------------------\n" + "| " + battlefield[8, 0] + " | " + battlefield[8, 1] + " | " + battlefield[8, 2] + " | " + battlefield[8, 3] + " | " + battlefield[8, 4] + " | " + battlefield[8, 5] + " | " + battlefield[8, 6] + " | " + battlefield[8, 7] + " | " + battlefield[8, 8] + " | " + battlefield[8, 9] + " |\n" + "----------------------------------------\n" + "| " + battlefield[9, 0] + " | " + battlefield[9, 1] + " | " + battlefield[9, 2] + " | " + battlefield[9, 3] + " | " + battlefield[9, 4] + " | " + battlefield[9, 5] + " | " + battlefield[9, 6] + " | " + battlefield[9, 7] + " | " + battlefield[9, 8] + " | " + battlefield[9, 9] + " |\n" + "----------------------------------------\n"; } } }
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 UberFrba.Abm_Chofer; using UberFrba.Abm_Turno; namespace UberFrba.Abm_Automovil { public partial class AltaAutomovil : Form { public Chofer choferElegido; public Turno turnoElegido; public AltaAutomovil() { InitializeComponent(); } private void btnSelecTurno_Click(object sender, EventArgs e) { GrillaTurno_Auto grillaTurno = new GrillaTurno_Auto(this,"alta"); grillaTurno.Show(); } private void bntSelectChofer_Click(object sender, EventArgs e) { GrillaChofer_Auto grillaChofer = new GrillaChofer_Auto(this,"seleccion"); grillaChofer.Show(); } private void btnGuardar_Click(object sender, EventArgs e) { int contadorErrores = 0; if (cmbMarca.SelectedValue == null) { contadorErrores++; errorMarca.Text = "El campo no puede ser vacio"; } errorModelo.Text = Automovil.validarModelo(txtModelo.Text); if (errorModelo.Text != "") contadorErrores++; errorPatente.Text = Automovil.validarPatente(txtPatente.Text); if (errorPatente.Text != "") contadorErrores++; errorTurno.Text = Automovil.validarTurno(txtTurno.Text); if (errorTurno.Text != "") contadorErrores++; errorChofer.Text = Automovil.validarChofer(txtChofer.Text); if (errorChofer.Text != "") contadorErrores++; //Si no hay errores, se intenta guardar el nuevo cliente if (contadorErrores == 0) { Automovil autoAGrabar = new Automovil(); autoAGrabar.Marca = (Int32)(cmbMarca.SelectedValue); autoAGrabar.Modelo = txtModelo.Text; autoAGrabar.Patente = txtPatente.Text; autoAGrabar.Chofer = choferElegido.Telefono; autoAGrabar.Turno = turnoElegido.Codigo; autoAGrabar.Activo = 1; String[] respuesta = Automovil.grabarAuto(autoAGrabar); if (respuesta[0] == "Error") { lblErrorBaseDatos.Text = respuesta[1]; grpErrorBaseDatos.Visible = true; } else { MessageBox.Show(respuesta[1], "Operación exitosa", MessageBoxButtons.OK); lblErrorBaseDatos.Text = String.Empty; grpErrorBaseDatos.Visible = false; } } } public void cambiarChofer() { txtChofer.Text = choferElegido.Nombre + " " + choferElegido.Apellido; } public void cambiarTurno() { txtTurno.Text = turnoElegido.Descripcion + " (" + turnoElegido.HoraInicio.ToString() + " a " + turnoElegido.HoraFin.ToString() + ")"; } private void AltaAutomovil_Load(object sender, EventArgs e) { DataTable marcasDt = Automovil.traerMarcas(); cmbMarca.DataSource = marcasDt; cmbMarca.DisplayMember = "Marca_Nombre"; cmbMarca.ValueMember = "Marca_Codigo"; } private void btnLimpiar_Click(object sender, EventArgs e) { txtPatente.Text = ""; txtModelo.Text = ""; txtChofer.Text = ""; txtTurno.Text = ""; choferElegido = null; turnoElegido = null; errorPatente.Text = ""; errorModelo.Text = ""; errorChofer.Text = ""; errorTurno.Text = ""; errorMarca.Text = ""; lblErrorBaseDatos.Text = String.Empty; grpErrorBaseDatos.Visible = false; } } }
using HardwareInventoryManager.Helpers; using HardwareInventoryManager.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HardwareInventoryManager.Helpers.User { public interface IUserService { IQueryable<Models.ApplicationUser> GetUsers(); Models.ApplicationUser GetUserById(string id); ApplicationUser GetUserByEmail(string email); ApplicationUser EditUser(ApplicationUser user); EnumHelper.Roles GetCurrentUserRoleById(string userId); ApplicationUser CreateUser(ApplicationUser user); void UpdateUserTenants(); string[] Errors { get; set; } } }
using Tresana.Data.Entities; using System.Data.Entity; namespace Tresana.Data.DataAccess { public class TresanaContext : DbContext { public DbSet<User> Users { get; set; } public DbSet<Task> Tasks { get; set; } public DbSet<Project> Projects { get; set; } public DbSet<Status> Statuses { get; set; } public DbSet<Priority> Priorities { get; set; } public DbSet<Team> Teams { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abstraction { class Car : Vehicle { public override string Start() { return "Vızır vızır"; } public override string Stop() { return "Şıp"; } public override string ToString() { return "Araba"; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using ObjectDumper; namespace CSharpUtils.Utils { /// <summary> /// Class that makes it easier to generate crash logs with enough information to solve the issue. /// </summary> public class ExceptionDumper { /// <summary> /// The location where the files are stored. /// </summary> public static string directory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); /// <summary> /// The exception. /// </summary> private Exception exception; /// <summary> /// The extra data. /// </summary> private Dictionary<string, object> data = new Dictionary<string, object>(); public ExceptionDumper(Exception e) { exception = e; } /// <summary> /// Add a variable to the crash log. /// </summary> public void Dump(string key, object value) { data.Add(key, value); } /// <summary> /// Add the contents of a file to the crash log. /// </summary> public void DumpFile(string key, string path) { string value = ""; try { using (StreamReader reader = File.OpenText(path)) { value = reader.ReadToEnd(); } } catch (Exception) { value = "Unable to read file"; } Dump(key, value); } public string Format() { using (StringWriter writer = new StringWriter()) { writer.WriteLine("===== Exception ====="); writer.WriteLine(exception.ToString()); writer.WriteLine(); writer.WriteLine("===== Dump ====="); foreach (KeyValuePair<string, object> data in this.data) { Dumper.Dump(data.Value, data.Key, writer); writer.WriteLine(); } return writer.GetStringBuilder().ToString(); } } /// <summary> /// Save the error log. /// </summary> /// <returns>The path of the log</returns> public string SaveToFile() { Directory.CreateDirectory(directory); string filename = Path.Combine( directory, string.Format("ErrorReport {0}.log", DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss fff")) ); File.WriteAllText(filename, Format()); return filename; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FantasyStore.Domain; using FantasyStore.Infrastructure.Repositories; namespace FantasyStore.Infrastructure { public class UnitOfWork { private readonly FantasyStoreDbContext _context = new FantasyStoreDbContext(); private OrderRepository _orderRepository; private ProductRepository _productRepository; private AddressRepository _addressRepository; private CartRepository _cartRepository; private ItemRepository _items; private UserRepository _users; private PaymentRepository _payments; private WishListRepository _wishLists; private ProductFieldValueRepository _fieldValues; public ProductFieldValueRepository FieldValues { get { return _fieldValues ?? (_fieldValues = new ProductFieldValueRepository(_context)); } } public WishListRepository WishLists { get { return _wishLists ?? (_wishLists = new WishListRepository(_context)); } } public ItemRepository Items { get { return _items ?? (_items = new ItemRepository(_context)); } } public PaymentRepository Payments { get { return _payments ?? (_payments = new PaymentRepository(_context)); } } public UserRepository Users { get { return _users ?? (_users = new UserRepository(_context)); } } public CartRepository Carts { get { return _cartRepository ?? (_cartRepository = new CartRepository(_context)); } } public ProductRepository Products { get { return _productRepository ?? (_productRepository = new ProductRepository(_context)); } } public OrderRepository Orders { get { return _orderRepository ?? (_orderRepository = new OrderRepository(_context)); } } public AddressRepository Addresses { get { return _addressRepository ?? (_addressRepository = new AddressRepository(_context)); } } public void Commit() { _context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Utilities.CustomException; using Utilities.Enums; using Utilities.Implementation.FileManagement.Result; using Utilities.Interface; namespace Utilities.Implementation.FileManagement.Manager { /// <summary> /// Clase encargada de la lectura y escritura de archivos planos /// </summary> public class FileTxtManager : IFileManager { /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="path"></param> /// <param name="extencion"></param> /// <returns>retorna el objeto de repuesta</returns> public T Read<T>(string fullName, ExtencionFile extencion) where T : FileResult { if (typeof(T) != typeof(FileTxtResult)) { throw new CofingTypeNotSupportedException(); } if (!fullName.EndsWith(extencion.ToString())) { throw new ExtencionNotSupportedException(); } using (StreamReader sr = new StreamReader(fullName)) { String line = sr.ReadToEnd(); return new FileTxtResult() { Path = fullName, Extencion = extencion, TextValue = line } as T; } } /// <summary> /// Metodo encarado de hacer la lectura del texto /// a partir de arreglo de bytes /// </summary> /// <typeparam name="T"></typeparam> /// <param name="bytes"></param> /// <param name="extencion"></param> /// <returns></returns> public T ReadBytes<T>(byte[] bytes, ExtencionFile extencion) where T : FileResult { if (typeof(T) != typeof(FileTxtResult)) { throw new CofingTypeNotSupportedException(); } string line = Encoding.UTF8.GetString(bytes, 0, bytes.Length); return new FileTxtResult() { Path = "", Extencion = extencion, TextValue = line } as T; } /// <summary> /// Metodo sobre escrito pero no implmentado /// </summary> /// <param name="path"></param> /// <param name="extencion"></param> /// <returns></returns> public byte[] ReadBytesPath(string path, ExtencionFile extencion) { throw new NotImplementedException(); } /// <summary> /// Metoto encargado de grabar un archivo plano /// </summary> /// <param name="fullName">nombre completo donde sera almacenado el archivo</param> /// <param name="bytes">arreglo de bytes que se almacenaran</param> /// <param name="extencion">extencion de archivo a almacenar</param> /// <returns>retorna si fue o no capas de grabar</returns> public bool Write(string fullName, byte[] bytes, ExtencionFile extencion) { if (!fullName.EndsWith(extencion.ToString())) { throw new ExtencionNotSupportedException(); } String str = Encoding.Default.GetString(bytes); if (!String.IsNullOrEmpty(str)) { using (StreamWriter file = new StreamWriter(fullName)) { file.Write(str); return true; } } return false; } } }
using Microsoft.Xna.Framework; namespace SprintFour.Levels { public interface ILevel { void Update(); bool BlockUnder(Rectangle bounds); bool BlockUnder(int x, int y); } }
using System; using System.Collections.Generic; using System.Linq; using Psub.DTO.Entities; using Psub.DataAccess.Abstract; using Psub.DataService.Abstract; using Psub.Domain.Entities; namespace Psub.DataService.Concrete { public class PublicationSectionService : IPublicationSectionService { private readonly IRepository<Section> _publicationSelectionRepository; public PublicationSectionService(IRepository<Section> publicationSelectionRepository) { _publicationSelectionRepository = publicationSelectionRepository; } public PublicationSectionDTO GetPublicationSectionDTOById(int id) { var publicationSectionDTO = _publicationSelectionRepository.Get(id); return new PublicationSectionDTO { Id = publicationSectionDTO.Id, Name = publicationSectionDTO.Name }; } public PublicationSectionDTO GetPublicationSectionDTOByName(string name) { var publicationSectionDTO = _publicationSelectionRepository.Query().FirstOrDefault(m => m.Name == name); if (publicationSectionDTO != null) return new PublicationSectionDTO { Id = publicationSectionDTO.Id, Name = publicationSectionDTO.Name }; return new PublicationSectionDTO(); } public IEnumerable<PublicationSectionDTO> GetPublicationSectionDTOList() { return _publicationSelectionRepository.Query().Select(m => new PublicationSectionDTO { Id = m.Id, Name = m.Name, PublicationMainSection = new PublicationMainSectionDTO { Id = m.MainSection.Id, Name = m.MainSection.Name } }).ToList(); } public int SaveOrUpdate(PublicationSectionDTO publicationSectionDTO) { return _publicationSelectionRepository.SaveOrUpdate(new Section { Id = 0, Name = publicationSectionDTO.Name, MainSection = new MainSection { Id = publicationSectionDTO.PublicationMainSection.Id } }); } public void Delete(int id) { // if (_publicationSelectionRepository.Get(id) != null) _publicationSelectionRepository.Delete(id); } } }
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Text; namespace VACE_Controlling.Outlookbar { public class ContentPanel : Panel { public OutlookBar outlookBar; public ContentPanel() { // initial state Visible = true; this.BorderStyle = BorderStyle.None; } } }
using System; using System.Collections.Generic; using Assets.Scripts.Core.ConstantsContainers; using Assets.Scripts.Units; namespace Assets.Scripts.Configs { [Serializable] public class SpawnWave { [ChooseFromList(typeof(UnitType))] public List<string> Mobs; public float PrepareTime; } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ApplicationConfiguration.cs" company="Soloplan GmbH"> // Copyright (c) Soloplan GmbH. All rights reserved. // Licensed under the MIT License. See License-file in the project root for license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Soloplan.WhatsON.Configuration { using System.Collections.Generic; using System.Linq; using Soloplan.WhatsON.Model; /// <summary> /// Holds the serializable configuration. /// </summary> public class ApplicationConfiguration { /// <summary> /// Gets or sets a value indicating whether dark theme is enabled. /// </summary> public bool DarkThemeEnabled { get; set; } /// <summary> /// Gets or sets a value indicating whether icon on taskbar should be shown. /// </summary> public bool ShowInTaskbar { get; set; } /// <summary> /// Gets or sets a value indicating whether App is always on top. /// </summary> public bool AlwaysOnTop { get; set; } /// <summary> /// Gets or sets a value indicating whether App is starts up minimized. /// </summary> public bool OpenMinimized { get; set; } /// <summary> /// Gets or sets a view style, for now normal/compact are available and they only control the spacing of items. /// </summary> public ViewStyle ViewStyle { get; set; } /// <summary> /// Gets the connectors configuration. /// </summary> public IList<ConnectorConfiguration> ConnectorsConfiguration { get; } = new List<ConnectorConfiguration>(); /// <summary> /// Gets the notification configuration. /// </summary> public NotificationConfiguration NotificationConfiguration { get; } = new NotificationConfiguration(); /// <summary> /// Gets the notification configuration from the per connector settings or the global settings.. /// </summary> /// <param name="connectorConfiguration">The connector configuration.</param> /// <returns>The notification configuration.</returns> public NotificationConfiguration GetNotificationConfiguration(ConnectorConfiguration connectorConfiguration) { // firstly check if the config item exists to prevent creation it "on access". var notificationVisibilityConfigItem = connectorConfiguration.ConfigurationItems.FirstOrDefault(ci => ci.Key == Connector.NotificationsVisbility); if (notificationVisibilityConfigItem == null) { return this.NotificationConfiguration; } var connectorNotificationConfiguration = notificationVisibilityConfigItem.GetOrCreateConnectorNotificationConfiguration(); return connectorNotificationConfiguration.UseGlobalNotificationSettings ? this.NotificationConfiguration : connectorNotificationConfiguration; } } }
namespace Task03_Media_System_Console_Test.Models { using System; using System.Collections.Generic; [Serializable] public class AlbumApiModel { public int Id { get; set; } public string Title { get; set; } public int? Year { get; set; } public string Producer { get; set; } public ICollection<int> ArtistsIds; public ICollection<int> SongsIds; } }
namespace CVBuilder.Core.Models { public class ProjectPortofolio : GeneralInfo { public string ProjectName { get; set; } public Period PeriodTime { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GridSystem : MonoBehaviour { public GameObject tilePrefab; public TileLevel[] themes; public int currentTheme; public Cell[,] Grid; public int level; // Start is called before the first frame update void Start() { SetUpGrid(); } private void Update() { //level = Utils.currentlevel; if (Input.GetKeyDown(KeyCode.Space)) { UpdateTileTheme(currentTheme < themes.Length - 1 ? currentTheme += 1 : 0); } } public void SetUpGrid() { Utils.Vertical = (int)Camera.main.orthographicSize; Utils.Horizontal = Utils.Vertical * (Screen.width / Screen.height); Utils.Colums = Utils.Horizontal * 2; Utils.Rows = Utils.Vertical * 2; Grid = new Cell[Utils.Colums, Utils.Rows]; for (int i = 0; i < Utils.Colums; i++) for (int j = 0; j < Utils.Rows; j++) Grid[i, j] = new Cell(tilePrefab, themes[currentTheme], i, j); } public void UpdateTileTheme(int index) { currentTheme = index; for (int i = 0; i < Utils.Colums; i++) { for (int j = 0; j < Utils.Rows; j++) { Grid[i, j].UpdateTileTheme(themes[currentTheme]); } } } public void NewLevel() { level++; } }
namespace OC.Authentication.Login { public class Chain { /** @var PreLoginHookCommand */ private PreLoginHookCommand preLoginHookCommand; /** @var UserDisabledCheckCommand */ private UserDisabledCheckCommand userDisabledCheckCommand; /** @var UidLoginCommand */ private UidLoginCommand uidLoginCommand; /** @var EmailLoginCommand */ private EmailLoginCommand emailLoginCommand; /** @var LoggedInCheckCommand */ private LoggedInCheckCommand loggedInCheckCommand; /** @var CompleteLoginCommand */ private CompleteLoginCommand completeLoginCommand; /** @var CreateSessionTokenCommand */ private CreateSessionTokenCommand createSessionTokenCommand; /** @var ClearLostPasswordTokensCommand */ private ClearLostPasswordTokensCommand clearLostPasswordTokensCommand; /** @var UpdateLastPasswordConfirmCommand */ private UpdateLastPasswordConfirmCommand updateLastPasswordConfirmCommand; /** @var SetUserTimezoneCommand */ private SetUserTimezoneCommand setUserTimezoneCommand; /** @var TwoFactorCommand */ private TwoFactorCommand twoFactorCommand; /** @var FinishRememberedLoginCommand */ private FinishRememberedLoginCommand finishRememberedLoginCommand; public Chain (PreLoginHookCommand preLoginHookCommand, UserDisabledCheckCommand userDisabledCheckCommand, UidLoginCommand uidLoginCommand, EmailLoginCommand emailLoginCommand, LoggedInCheckCommand loggedInCheckCommand, CompleteLoginCommand completeLoginCommand, CreateSessionTokenCommand createSessionTokenCommand, ClearLostPasswordTokensCommand clearLostPasswordTokensCommand, UpdateLastPasswordConfirmCommand updateLastPasswordConfirmCommand, SetUserTimezoneCommand setUserTimezoneCommand, TwoFactorCommand twoFactorCommand, FinishRememberedLoginCommand finishRememberedLoginCommand ) { this.preLoginHookCommand = preLoginHookCommand; this.userDisabledCheckCommand = userDisabledCheckCommand; this.uidLoginCommand = uidLoginCommand; this.emailLoginCommand = emailLoginCommand; this.loggedInCheckCommand = loggedInCheckCommand; this.completeLoginCommand = completeLoginCommand; this.createSessionTokenCommand = createSessionTokenCommand; this.clearLostPasswordTokensCommand = clearLostPasswordTokensCommand; this.updateLastPasswordConfirmCommand = updateLastPasswordConfirmCommand; this.setUserTimezoneCommand = setUserTimezoneCommand; this.twoFactorCommand = twoFactorCommand; this.finishRememberedLoginCommand = finishRememberedLoginCommand; } public LoginResult process(LoginData loginData) { var chain = this.preLoginHookCommand; chain .setNext(this.userDisabledCheckCommand) .setNext(this.uidLoginCommand) .setNext(this.emailLoginCommand) .setNext(this.loggedInCheckCommand) .setNext(this.completeLoginCommand) .setNext(this.createSessionTokenCommand) .setNext(this.clearLostPasswordTokensCommand) .setNext(this.updateLastPasswordConfirmCommand) .setNext(this.setUserTimezoneCommand) .setNext(this.twoFactorCommand) .setNext(this.finishRememberedLoginCommand); return chain.process(loginData); } } }
using Juego.backend; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Juego { class BaseJuego { DetectarBatalla db = new DetectarBatalla(); MovmentHeroe mv = new MovmentHeroe(); MovmentMonster mvh = new MovmentMonster(); Random randomPosition = new Random(); static int Size = 0; IMostrar _Mostrar; static int xHeroe, yHeroe; public BaseJuego(IMostrar Mostrar,int size) { Size = size; _Mostrar = Mostrar; } ObjectGeneric[,] Dungeon; public void Start() { Dungeon = new ObjectGeneric[Size, Size]; InicializarDungeon(Dungeon); SpawnMonsters(Dungeon, (Size / 10) * 4); SpawnHeroe(Dungeon); _Mostrar.VisualizarDungeon(Dungeon, Size-1); for (int a = 0; a < 100; a++) { WhilePlay(); } } public void WhilePlay() { Dungeon = mv.Movimiento(Dungeon, xHeroe, yHeroe, Size - 1); UPDATEMovimientosHeroes(); MovimientosMonstruos(); _Mostrar.VisualizarDungeon(Dungeon, Size-1); if (db.Detectar(xHeroe, yHeroe, Dungeon)) { List<Monsters> Monstruos = db.DetectarNumMonsters(xHeroe, yHeroe, Dungeon); Heroe h = (Heroe)Dungeon[xHeroe, yHeroe]; _Mostrar.VisualizarBatalla(Monstruos, h); _Mostrar.VisualizarDungeon(Dungeon, Size - 1); } } public void MovimientosMonstruos() { for (int x = 1; x < Size - 1; x++) { for (int y = 1; y < Size - 1; y++) { if (Dungeon[x, y].Body == '?') { Dungeon = mvh.Movimiento(Dungeon, x, y, Size - 1); } } } } public void UPDATEMovimientosHeroes() { for (int x = 1; x < Size - 1; x++) { for (int y = 1; y < Size - 1; y++) { if (Dungeon[x, y].Body == '#') { xHeroe = x; yHeroe = y; } } } } private void SpawnMonsters(ObjectGeneric[,] dungeon, int Monsters) { int x, y; for (int a = 0; a < Monsters; a++) { x = randomPosition.Next(1, Size - 1); y = randomPosition.Next(1, Size - 1); Dungeon[x, y] = new Monsters("Monster", 50, '?'); } } private void SpawnHeroe(ObjectGeneric[,] dungeon) { xHeroe = randomPosition.Next(1, Size - 1); yHeroe = randomPosition.Next(1, Size - 1); Dungeon[xHeroe, yHeroe] = new Heroe("Heroe", 200, '#'); } private void InicializarDungeon(ObjectGeneric[,] dungeon) { for (int x = 0; x < Size; x++) { for (int y = 0; y < Size; y++) { Dungeon[x, y] = new ObjectsNulls(' '); } } } } }
using System; using System.Threading; using System.Threading.Tasks; using Cogito.Kademlia.Core; namespace Cogito.Kademlia { /// <summary> /// Implements a fixed Kademlia routing table. /// </summary> /// <typeparam name="TKNodeId"></typeparam> /// <typeparam name="TKNodeData"></typeparam> public class KFixedRoutingTable<TKNodeId, TKNodeData> : KTable, IKRoutingTable<TKNodeId, TKNodeData> where TKNodeId : struct, IKNodeId<TKNodeId> { readonly TKNodeId self; readonly IKNodeProtocol<TKNodeId, TKNodeData> protocol; readonly int k; readonly KBucket<TKNodeId, TKNodeData>[] buckets; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="self"></param> /// <param name="protocol"></param> /// <param name="k"></param> public KFixedRoutingTable(TKNodeId self, IKNodeProtocol<TKNodeId, TKNodeData> protocol, int k = 20) { this.self = self; this.protocol = protocol; this.k = k; if (self.DistanceSize % 8 != 0) throw new ArgumentException("NodeId must have a distance size which is a multiple of 8."); buckets = new KBucket<TKNodeId, TKNodeData>[self.DistanceSize]; for (var i = 0; i < buckets.Length; i++) buckets[i] = new KBucket<TKNodeId, TKNodeData>(k); } /// <summary> /// Gets the fixed size of the routing table buckets. /// </summary> public int K => k; /// <summary> /// Gets the bucket associated with the specified node ID. /// </summary> /// <param name="nodeId"></param> /// <returns></returns> internal KBucket<TKNodeId, TKNodeData> GetBucket(TKNodeId nodeId) { return buckets[GetBucketIndex(self, nodeId)]; } /// <summary> /// Updates the reference to the node within the table. /// </summary> /// <param name="nodeId"></param> /// <param name="nodeData"></param> /// <param name="nodeEvents"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public ValueTask TouchAsync(TKNodeId nodeId, TKNodeData nodeData = default, IKNodeEvents nodeEvents = null, CancellationToken cancellationToken = default) { return GetBucket(nodeId).TouchAsync(nodeId, nodeData, nodeEvents, protocol, cancellationToken); } } /// <summary> /// Describes a Kademlia routing table. /// </summary> public abstract class KTable { /// <summary> /// Calculates the bucket index that should be used for the <paramref name="other"/> node in a table owned by <paramref name="self"/>. /// </summary> /// <typeparam name="TKNodeId"></typeparam> /// <param name="self"></param> /// <param name="other"></param> /// <returns></returns> internal static int GetBucketIndex<TKNodeId>(TKNodeId self, TKNodeId other) where TKNodeId : IKNodeId<TKNodeId> { if (self.Equals(other)) throw new ArgumentException("Cannot get bucket for own node."); var s = self.DistanceSize / 8; var d = (Span<byte>)stackalloc byte[s]; self.CalculateDistance(other, d); var z = ((ReadOnlySpan<byte>)d).CountLeadingZeros(); return other.DistanceSize - z - 1; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Requestrr.WebApi.Extensions; using Requestrr.WebApi.RequestrrBot.Movies; using Requestrr.WebApi.RequestrrBot.TvShows; namespace Requestrr.WebApi.RequestrrBot.DownloadClients.Ombi { public class OmbiClient : IMovieRequester, IMovieSearcher, ITvShowSearcher, ITvShowRequester { private IHttpClientFactory _httpClientFactory; private readonly ILogger<OmbiClient> _logger; private OmbiSettingsProvider _ombiSettingsProvider; private OmbiSettings OmbiSettings => _ombiSettingsProvider.Provide(); private string BaseURL => GetBaseURL(OmbiSettings); public OmbiClient(IHttpClientFactory httpClientFactory, ILogger<OmbiClient> logger, OmbiSettingsProvider OmbiSettingsProvider) { _httpClientFactory = httpClientFactory; _logger = logger; _ombiSettingsProvider = OmbiSettingsProvider; } public static async Task TestConnectionAsync(HttpClient httpClient, ILogger<OmbiClient> logger, OmbiSettings settings) { if (!string.IsNullOrWhiteSpace(settings.BaseUrl) && !settings.BaseUrl.StartsWith("/")) { throw new Exception("Invalid base URL, must start with /"); } var testSuccessful = false; try { var response = await HttpGetAsync(httpClient, settings, $"{GetBaseURL(settings)}/api/v1/Settings/ombi"); if (response.StatusCode == HttpStatusCode.Unauthorized) { throw new Exception("Invalid api key"); } else if (response.StatusCode == HttpStatusCode.NotFound) { throw new Exception("Invalid host and/or port"); } try { var responseString = await response.Content.ReadAsStringAsync(); dynamic jsonResponse = JObject.Parse(responseString); if (!jsonResponse.baseUrl.ToString().Equals(settings.BaseUrl, StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("Base url does not match what is set in Ombi"); } } catch { throw new Exception("Base url does not match what is set in Ombi"); } testSuccessful = true; } catch (HttpRequestException ex) { logger.LogWarning(ex, "Error while testing Ombi connection: " + ex.Message); throw new Exception("Invalid host and/or port"); } catch (System.Exception ex) { logger.LogWarning(ex, "Error while testing Ombi connection: " + ex.Message); if (ex.GetType() == typeof(System.Exception)) { throw; } else { throw new Exception("Invalid host and/or port"); } } if (!testSuccessful) { throw new Exception("Invalid host and/or port"); } } public async Task<MovieRequestResult> RequestMovieAsync(MovieRequest request, Movie movie) { var retryCount = 0; while (retryCount <= 5) { try { var ombiUser = await FindLinkedOmbiUserAsync(request.User.UserId, request.User.Username); if (ombiUser.CanRequestMovies && ombiUser.MoviesQuotaRemaining > 0) { var response = await HttpPostAsync(ombiUser, $"{BaseURL}/api/v1/Request/Movie", JsonConvert.SerializeObject(new { theMovieDbId = movie.TheMovieDbId })); await response.ThrowIfNotSuccessfulAsync("OmbiCreateMovieRequest failed", x => x.error); return new MovieRequestResult(); } return new MovieRequestResult { WasDenied = true }; } catch (System.Exception ex) { _logger.LogError(ex, $"An error while requesting movie \"{movie.Title}\" from Ombi: " + ex.Message); retryCount++; await Task.Delay(1000); } } throw new System.Exception("An error occurred while requesting a movie from oOmbimbi"); } public async Task<Movie> SearchMovieAsync(MovieRequest request, int theMovieDbId) { var retryCount = 0; while (retryCount <= 5) { try { var response = await HttpGetAsync($"{BaseURL}/api/v1/search/movie/info/{theMovieDbId}"); await response.ThrowIfNotSuccessfulAsync("OmbiMovieSearchByMovieDbId failed", x => x.error); var jsonResponse = await response.Content.ReadAsStringAsync(); var jsonMovie = JsonConvert.DeserializeObject<JSONMovie>(jsonResponse); var convertedMovie = Convert(jsonMovie); return convertedMovie?.TheMovieDbId == theMovieDbId.ToString() ? convertedMovie : null; } catch (System.Exception ex) { _logger.LogError(ex, $"An error occurred while searching for a movie by tmdbId \"{theMovieDbId}\" from Ombi: " + ex.Message); retryCount++; await Task.Delay(1000); } } throw new System.Exception("An error occurred while searching for a movie by tmdbId from Ombi"); } public async Task<IReadOnlyList<Movie>> SearchMovieAsync(MovieRequest request, string movieName) { var retryCount = 0; while (retryCount <= 5) { try { var response = await HttpGetAsync($"{BaseURL}/api/v1/search/movie/{movieName}"); await response.ThrowIfNotSuccessfulAsync("OmbiMovieSearch failed", x => x.error); var jsonResponse = await response.Content.ReadAsStringAsync(); var movies = JsonConvert.DeserializeObject<List<JSONMovie>>(jsonResponse).ToArray(); return movies.Select(Convert).ToArray(); } catch (System.Exception ex) { _logger.LogError(ex, "An error occurred while searching for movies from Ombi: " + ex.Message); retryCount++; await Task.Delay(1000); } } throw new System.Exception("An error occurred while searching for movies from Ombi"); } public Task<MovieDetails> GetMovieDetails(MovieRequest request, string theMovieDbId) { return TheMovieDb.GetMovieDetailsAsync(_httpClientFactory.CreateClient(), theMovieDbId, _logger); } public async Task<Movie> GetMovieAsync(int movieId) { var retryCount = 0; while (retryCount <= 5) { try { var response = await HttpGetAsync($"{BaseURL}/api/v1/search/movie/info/{movieId.ToString()}"); await response.ThrowIfNotSuccessfulAsync("OmbiGetMovieInfo failed", x => x.error); var jsonResponse = await response.Content.ReadAsStringAsync(); var jsonMovie = JsonConvert.DeserializeObject<JSONMovie>(jsonResponse); return Convert(jsonMovie); } catch (System.Exception ex) { _logger.LogError(ex, "An error occurred while searching for a movie from Ombi: " + ex.Message); retryCount++; await Task.Delay(1000); } } throw new System.Exception("An error occurred while searching for a movie from Ombi"); } public async Task<Dictionary<int, Movie>> SearchAvailableMoviesAsync(HashSet<int> movieIds, System.Threading.CancellationToken token) { var retryCount = 0; while (retryCount <= 5 && !token.IsCancellationRequested) { try { var movies = new HashSet<Movie>(); foreach (var movieId in movieIds) { await Task.Delay(100); var movie = await GetMovieAsync(movieId); if (movie.Available) { movies.Add(movie); } } return movies.ToDictionary(x => int.Parse(x.TheMovieDbId), x => x); } catch (System.Exception ex) { _logger.LogError(ex, "An error occurred while searching for availables movies from Ombi: " + ex.Message); retryCount++; await Task.Delay(1000, token); } } throw new System.Exception("An error occurred while searching for availables movies from Ombi"); } public async Task<TvShowRequestResult> RequestTvShowAsync(TvShowRequest request, TvShow tvShow, TvSeason season) { var retryCount = 0; while (retryCount <= 5) { try { var ombiUser = await FindLinkedOmbiUserAsync(request.User.UserId, request.User.Username); var jsonTvShow = await FindTvShowByTheTvDbIdAsync(tvShow.TheTvDbId.ToString()); var wantedSeasonIds = season is AllTvSeasons ? new HashSet<int>(tvShow.Seasons.OfType<NormalTvSeason>().Select(x => x.SeasonNumber)) : season is FutureTvSeasons ? new HashSet<int>() : new HashSet<int> { season.SeasonNumber }; var episodeToRequestCount = jsonTvShow.seasonRequests.Sum(s => wantedSeasonIds.Contains(s.seasonNumber) && s.CanBeRequested() ? s.episodes.Where(x => x.CanBeRequested()).Count() : 0); if (ombiUser.CanRequestTvShows && ombiUser.TvEpisodeQuotaRemaining > 0) { var response = await HttpPostAsync(ombiUser, $"{BaseURL}/api/v1/Request/Tv", JsonConvert.SerializeObject(new { tvDbId = tvShow.TheTvDbId, requestAll = false, latestSeason = false, firstSeason = false, seasons = jsonTvShow.seasonRequests.Select(s => { var episodes = wantedSeasonIds.Contains(s.seasonNumber) && s.CanBeRequested() ? s.episodes.Where(x => x.CanBeRequested()).Select(e => new JSONTvEpisode { episodeNumber = e.episodeNumber }) : Array.Empty<JSONTvEpisode>(); episodes = episodes.Take(ombiUser.TvEpisodeQuotaRemaining); ombiUser.TvEpisodeQuotaRemaining -= episodes.Count(); return new { seasonNumber = s.seasonNumber, episodes = episodes, }; }), })); await response.ThrowIfNotSuccessfulAsync("OmbiCreateTvShowRequest failed", x => x.error); return new TvShowRequestResult(); } return new TvShowRequestResult { WasDenied = true }; } catch (System.Exception ex) { _logger.LogError(ex, $"An error while requesting tv show \"{tvShow.Title}\" from Ombi: " + ex.Message); retryCount++; await Task.Delay(1000); } } throw new System.Exception("Something went wrong while requesting a tv show from Ombi"); } public async Task<TvShow> GetTvShowDetailsAsync(TvShowRequest request, int TheTvDbId) { var retryCount = 0; while (retryCount <= 5) { try { var jsonTvShow = await FindTvShowByTheTvDbIdAsync(TheTvDbId.ToString()); return Convert(jsonTvShow); } catch (System.Exception ex) { _logger.LogError(ex, "An error occurred while getting details for a tv show from Ombi: " + ex.Message); retryCount++; await Task.Delay(1000); } } throw new System.Exception("An error occurred while getting details for a tv show from Ombi"); } public async Task<IReadOnlyList<TvShow>> GetTvShowDetailsAsync(HashSet<int> tvShowIds, System.Threading.CancellationToken token) { var retryCount = 0; while (retryCount <= 5 && !token.IsCancellationRequested) { try { var tvShows = new List<TvShow>(); foreach (var showId in tvShowIds) { await Task.Delay(100); try { var show = await GetTvShowDetailsAsync(new TvShowRequest(null, int.MinValue), showId); tvShows.Add(show); } catch { // Ignore } } return tvShows.Where(x => x != null).ToArray(); } catch (System.Exception ex) { _logger.LogError(ex, "An error occurred while getting tv show details from Ombi: " + ex.Message); retryCount++; await Task.Delay(1000, token); } } throw new System.Exception("An error occurred while getting tv show details from Ombi"); } public async Task<SearchedTvShow> SearchTvShowAsync(TvShowRequest request, int tvDbId) { var retryCount = 0; while (retryCount <= 5) { try { var response = await HttpGetAsync($"{BaseURL}/api/v1/Search/Tv/info/{tvDbId}"); await response.ThrowIfNotSuccessfulAsync("OmbiSearchTvShowByTvDbId failed", x => x.error); var jsonResponse = await response.Content.ReadAsStringAsync(); var jsonTvShow = JsonConvert.DeserializeObject<JSONTvShow>(jsonResponse); var searchedTvShow = new SearchedTvShow { Title = jsonTvShow.title, Banner = jsonTvShow.banner, TheTvDbId = jsonTvShow.id, FirstAired = jsonTvShow.firstAired, }; return searchedTvShow.TheTvDbId == tvDbId ? searchedTvShow : null; } catch (System.Exception ex) { _logger.LogError(ex, $"An error occurred while searching for tv show by tvDbId \"{tvDbId}\" from Ombi: " + ex.Message); retryCount++; await Task.Delay(1000); } } throw new System.Exception("An error occurred while searching for tv show by tvDbId from Ombi"); } public async Task<IReadOnlyList<SearchedTvShow>> SearchTvShowAsync(TvShowRequest request, string tvShowName) { var retryCount = 0; while (retryCount <= 5) { try { var response = await HttpGetAsync($"{BaseURL}/api/v1/Search/Tv/{tvShowName}"); await response.ThrowIfNotSuccessfulAsync("OmbiSearchTvShow failed", x => x.error); var jsonResponse = await response.Content.ReadAsStringAsync(); var jsonTvShows = JsonConvert.DeserializeObject<List<JSONTvShow>>(jsonResponse).ToArray(); return jsonTvShows.Select(x => new SearchedTvShow { Title = x.title, Banner = x.banner, TheTvDbId = x.id, FirstAired = x.firstAired, }).ToArray(); } catch (System.Exception ex) { _logger.LogError(ex, $"An error occurred while searching for tv show \"{tvShowName}\" from Ombi: " + ex.Message); retryCount++; await Task.Delay(1000); } } throw new System.Exception("An error occurred while searching for tv show from Ombi"); } private async Task<JSONTvShow> FindTvShowByTheTvDbIdAsync(string theTvDbId) { var response = await HttpGetAsync($"{BaseURL}/api/v1/Search/tv/info/{theTvDbId}"); var jsonResponse = await response.Content.ReadAsStringAsync(); await response.ThrowIfNotSuccessfulAsync("OmbiFindTvShowTvDbId failed", x => x.error); return JsonConvert.DeserializeObject<JSONTvShow>(jsonResponse); } private Movie Convert(JSONMovie jsonMovie) { return new Movie { TheMovieDbId = jsonMovie.theMovieDbId, Title = jsonMovie.title, Available = jsonMovie.available, Quality = jsonMovie.quality, Requested = jsonMovie.requested, PlexUrl = jsonMovie.plexUrl, EmbyUrl = jsonMovie.embyUrl, Overview = jsonMovie.overview, PosterPath = !string.IsNullOrWhiteSpace(jsonMovie.posterPath) ? $"https://image.tmdb.org/t/p/w500{jsonMovie.posterPath}" : null, ReleaseDate = jsonMovie.releaseDate, }; } private TvShow Convert(JSONTvShow jsonTvShow) { if (jsonTvShow == null) { return null; } return new TvShow { TheTvDbId = jsonTvShow.id, Title = jsonTvShow.title, Quality = jsonTvShow.quality, PlexUrl = jsonTvShow.plexUrl, EmbyUrl = jsonTvShow.embyUrl, Overview = jsonTvShow.overview, Banner = jsonTvShow.banner, FirstAired = jsonTvShow.firstAired, Network = jsonTvShow.network, Status = jsonTvShow.status, WebsiteUrl = $"https://www.thetvdb.com/?id={jsonTvShow.id}&tab=series", HasEnded = !string.IsNullOrWhiteSpace(jsonTvShow.status) && jsonTvShow.status.Equals("ended", StringComparison.InvariantCultureIgnoreCase), Seasons = jsonTvShow.seasonRequests.Select(x => new NormalTvSeason { SeasonNumber = x.seasonNumber, IsAvailable = x.episodes.FirstOrDefault()?.available == true, IsRequested = x.episodes.All(x => x.CanBeRequested()) ? RequestedState.None : x.episodes.All(x => !x.CanBeRequested()) ? RequestedState.Full : RequestedState.Partial, }).ToArray(), IsRequested = jsonTvShow.requested || jsonTvShow.available, }; } public async Task<OmbiUser> FindLinkedOmbiUserAsync(string requesterUniqueId, string requesterUsername) { var response = await HttpGetAsync($"{BaseURL}/api/v1/Identity/Users"); var jsonResponse = await response.Content.ReadAsStringAsync(); await response.ThrowIfNotSuccessfulAsync("OmbiFindAllUsers failed", x => x.error); JSONOmbiUser[] allOmbiUsers = JsonConvert.DeserializeObject<List<JSONOmbiUser>>(jsonResponse).ToArray(); OmbiUser ombiUser = null; ombiUser = await FindLinkedUserByNotificationPreferencesAsync(requesterUniqueId, allOmbiUsers, ombiUser); if (ombiUser == null && !string.IsNullOrEmpty(OmbiSettings.ApiUsername)) { ombiUser = FindDefaultApiUserAsync(allOmbiUsers, requesterUsername); if (ombiUser == null) { return new OmbiUser { Username = "NO_ACCESS", ApiAlias = "NO_ACCESS", CanRequestMovies = false, MoviesQuotaRemaining = -1, CanRequestTvShows = false, TvEpisodeQuotaRemaining = -1, }; } } if (ombiUser == null) { return new OmbiUser { Username = "api", ApiAlias = requesterUsername, CanRequestMovies = true, MoviesQuotaRemaining = int.MaxValue, CanRequestTvShows = true, TvEpisodeQuotaRemaining = int.MaxValue, }; } return ombiUser; } private async Task<OmbiUser> FindLinkedUserByNotificationPreferencesAsync(string userUniqueId, JSONOmbiUser[] allOmbiUsers, OmbiUser ombiUser) { await Task.WhenAll(allOmbiUsers.Select(async x => { try { var notifResponse = await HttpGetAsync($"{BaseURL}/api/v1/Identity/notificationpreferences/{x.id.ToString()}"); var jsonNotifResponse = await notifResponse.Content.ReadAsStringAsync(); await notifResponse.ThrowIfNotSuccessfulAsync("OmbiFindUserNotificationPreferences failed", x => x.error); IEnumerable<dynamic> notificationPreferences = JArray.Parse(jsonNotifResponse); var matchingDiscordNotification = notificationPreferences.FirstOrDefault(n => n.agent == 1 && n.value.ToString().Trim().Equals(userUniqueId.Trim(), StringComparison.InvariantCultureIgnoreCase)); if (matchingDiscordNotification != null) { ombiUser = new OmbiUser { Username = x.userName, ApiAlias = !string.IsNullOrWhiteSpace(x.alias) ? x.alias : x.userName, CanRequestMovies = x.CanRequestMovie, MoviesQuotaRemaining = x.movieRequestQuota == null || !x.movieRequestQuota.hasLimit ? int.MaxValue : x.movieRequestQuota.remaining, CanRequestTvShows = x.CanRequestTv, TvEpisodeQuotaRemaining = x.episodeRequestQuota == null || !x.episodeRequestQuota.hasLimit ? int.MaxValue : x.episodeRequestQuota.remaining, }; } } catch (System.Exception ex) { _logger.LogError(ex, ex.Message); } })); return ombiUser; } private OmbiUser FindDefaultApiUserAsync(JSONOmbiUser[] allOmbiUsers, string requesterUsername) { OmbiUser ombiUser = null; var defaultApiUser = allOmbiUsers.FirstOrDefault(x => x.userName.Equals(OmbiSettings.ApiUsername, StringComparison.InvariantCultureIgnoreCase)); if (defaultApiUser != null) { ombiUser = new OmbiUser { Username = defaultApiUser.userName, ApiAlias = requesterUsername, CanRequestMovies = defaultApiUser.IsDisabled ? false : defaultApiUser.CanRequestMovie, MoviesQuotaRemaining = defaultApiUser.movieRequestQuota == null || !defaultApiUser.movieRequestQuota.hasLimit ? int.MaxValue : defaultApiUser.movieRequestQuota.remaining, CanRequestTvShows = defaultApiUser.IsDisabled ? false : defaultApiUser.CanRequestTv, TvEpisodeQuotaRemaining = defaultApiUser.episodeRequestQuota == null || !defaultApiUser.episodeRequestQuota.hasLimit ? int.MaxValue : defaultApiUser.episodeRequestQuota.remaining, }; } return ombiUser; } private static string GetBaseURL(OmbiSettings settings) { var protocol = settings.UseSSL ? "https" : "http"; return $"{protocol}://{settings.Hostname}:{settings.Port}{settings.BaseUrl}"; } private Task<HttpResponseMessage> HttpGetAsync(string url) { return HttpGetAsync(_httpClientFactory.CreateClient(), OmbiSettings, url); } private static async Task<HttpResponseMessage> HttpGetAsync(HttpClient client, OmbiSettings settings, string url) { var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Add("Accept", "application/json"); request.Headers.Add("ApiKey", settings.ApiKey); return await client.SendAsync(request); } private async Task<HttpResponseMessage> HttpPostAsync(OmbiUser ombiUser, string url, string content) { var apiAlias = Sanitize(ombiUser.ApiAlias); var apiUsername = Sanitize(ombiUser.Username); var postRequest = new StringContent(content); postRequest.Headers.Clear(); postRequest.Headers.Add("Content-Type", "application/json"); postRequest.Headers.Add("ApiKey", OmbiSettings.ApiKey); postRequest.Headers.Add("ApiAlias", !string.IsNullOrWhiteSpace(apiAlias) ? apiAlias : "Unknown"); postRequest.Headers.Add("UserName", !string.IsNullOrWhiteSpace(apiUsername) ? apiUsername : "api"); var client = _httpClientFactory.CreateClient(); return await client.PostAsync(url, postRequest); } private string Sanitize(string value) { if (string.IsNullOrWhiteSpace(value)) { return value; } return Regex.Replace(value, @"[^\u0000-\u007F]+", string.Empty); } public class JSONMovie { public string title { get; set; } public bool available { get; set; } public string quality { get; set; } public bool requested { get; set; } public bool approved { get; set; } public string plexUrl { get; set; } public string embyUrl { get; set; } public string overview { get; set; } public string posterPath { get; set; } public string releaseDate { get; set; } public string theMovieDbId { get; set; } } public class JSONTvShow { public int id { get; set; } public string title { get; set; } public string quality { get; set; } public string plexUrl { get; set; } public string embyUrl { get; set; } public string overview { get; set; } public bool requested { get; set; } public bool available { get; set; } public string banner { get; set; } public string firstAired { get; set; } public string network { get; set; } public string status { get; set; } public JSONTvSeason[] seasonRequests { get; set; } } public class JSONTvSeason { public int seasonNumber { get; set; } public JSONTvEpisode[] episodes { get; set; } public bool CanBeRequested() { return episodes.Any(e => e.CanBeRequested()); } } public class JSONTvEpisode { public int episodeNumber { get; set; } public bool available { get; set; } public bool requested { get; set; } public bool CanBeRequested() { return !available && !requested; } } public class JSONClaim { public string value { get; set; } public bool enabled { get; set; } } public class JSONRequestQuota { public bool hasLimit { get; set; } public int remaining { get; set; } } public class JSONOmbiUser { public string id { get; set; } public string userName { get; set; } public string alias { get; set; } public List<JSONClaim> claims { get; set; } public JSONRequestQuota episodeRequestQuota { get; set; } public JSONRequestQuota movieRequestQuota { get; set; } public bool IsAdmin => claims?.Any(x => x.value.Equals("admin", StringComparison.InvariantCultureIgnoreCase) && x.enabled) ?? false; public bool IsDisabled => claims?.Any(x => x.value.Equals("disabled", StringComparison.InvariantCultureIgnoreCase) && x.enabled) ?? false; public bool AutoApproveTv => claims?.Any(x => x.value.Equals("autoapprovetv", StringComparison.InvariantCultureIgnoreCase) && x.enabled) ?? false; public bool AutoApproveMovies => claims?.Any(x => x.value.Equals("autoapprovemovie", StringComparison.InvariantCultureIgnoreCase) && x.enabled) ?? false; public bool CanRequestTv => !IsDisabled && (IsAdmin || AutoApproveTv || (claims?.Any(x => x.value.Equals("requesttv", StringComparison.InvariantCultureIgnoreCase) && x.enabled) ?? false)); public bool CanRequestMovie => !IsDisabled && (IsAdmin || AutoApproveMovies || (claims?.Any(x => x.value.Equals("requestmovie", StringComparison.InvariantCultureIgnoreCase) && x.enabled) ?? false)); } public class OmbiUser { public string Username { get; set; } public string ApiAlias { get; set; } public bool CanRequestTvShows { get; set; } public int TvEpisodeQuotaRemaining { get; set; } public bool CanRequestMovies { get; set; } public int MoviesQuotaRemaining { get; set; } } } }
using System; using System.Collections.Generic; using IronPython.Compiler.Ast; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Py2Cs.Translators { public struct SyntaxResult<T> where T : class { private SyntaxResult(T syntax, IEnumerable<SyntaxTrivia> errors) { this.Syntax = syntax; this.Errors = errors; } public T Syntax { get; private set; } public IEnumerable<SyntaxTrivia> Errors { get; private set; } public bool IsError { get => Syntax == null; } static public implicit operator SyntaxResult<T>(T value) { return new SyntaxResult<T>(value, new SyntaxTrivia[] { }); } static public SyntaxResult<T> WithError(string error) { var comment = SyntaxFactory.Comment(error); return new SyntaxResult<T>(null, new[] { comment }); } static public SyntaxResult<T> WithErrors(IEnumerable<SyntaxTrivia> errors) { return new SyntaxResult<T>(null, errors); } } }
using MvcProjeKampi.DataAccessLayer.Abstract; using MvcProjeKampi.DataAccessLayer.Concrete.Repositories; using MvcProjeKampi.EntityLayer.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MvcProjeKampi.DataAccessLayer.EntityFramework { public class EfMessageDal : GenericRepository<Message>, IMessageDal { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Ornithology.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Contacto() { ViewBag.Message = "Deje su mensaje!"; return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.IO; namespace PnrAnalysis { /// <summary> /// 拼音转化 /// </summary> public class PinYingMange { /// <summary> /// 读取生僻字文件 /// </summary> /// <returns></returns> public static string ReadRare() { string rareFile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "rare.txt"; string result = string.Empty; try { if (File.Exists(rareFile)) { StreamReader sr = new StreamReader(rareFile, Encoding.Default); result = sr.ReadToEnd(); sr.Close(); } } catch (Exception ex) { } return result; } public static string PReplace(string strChar) { try { string strApp = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "pinying.txt"; if (File.Exists(strApp)) { StreamReader sr = new StreamReader(strApp, Encoding.Default); string strLine = sr.ReadLine(); string[] strArray = null; while (!string.IsNullOrEmpty(strLine)) { strArray = strLine.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (strArray != null && strArray.Length >= 2) { strChar = strChar.Replace(strArray[0].Trim(), strArray[1].Trim()); } } sr.Close(); } } catch (Exception) { } return strChar; } /// <summary> /// 替换错的拼音 /// </summary> /// <param name="strChar"></param> /// <returns></returns> public static string RepacePinyinChar(string strChar) { string oldChar = strChar; strChar = strChar.Replace("潇", "萧"); strChar = strChar.Replace("佚", "YI"); strChar = strChar.Replace("炜", "WEI"); strChar = strChar.Replace("萱", "XUAN"); strChar = strChar.Replace("羿", "YI"); strChar = strChar.Replace("睿", "RUI"); strChar = PReplace(strChar); if (strChar.ToUpper() == "ZUO") { byte[] chinase = null; strChar = chs2py.convert(oldChar, out chinase); } return strChar; } #region 汉字转拼方法1 /// <summary>汉字转拼音缩写</summary> /// <param name="str">要转换的汉字字符串</param> /// <returns>拼音缩写</returns> public static string GetSpellString(string str) { if (IsEnglishCharacter(str)) return str; string tempStr = ""; foreach (char c in str) { if ((int)c >= 33 && (int)c <= 126) {//字母和符号原样保留 tempStr += c.ToString(); } else {//累加拼音声母 tempStr += GetSpellChar(c.ToString()); } } return tempStr; } /// <summary> /// 判断是否字母 /// </summary> /// <param name="str"></param> /// <returns></returns> private static bool IsEnglishCharacter(String str) { CharEnumerator ce = str.GetEnumerator(); while (ce.MoveNext()) { char c = ce.Current; if ((c <= 0x007A && c >= 0x0061) == false && (c <= 0x005A && c >= 0x0041) == false) return false; } return true; } /// <summary> /// 判断是否有汉字 /// </summary> /// <param name="testString"></param> /// <returns></returns> public static bool HaveChineseCode(string testString) { if (Regex.IsMatch(testString, @"[\u4e00-\u9fa5]+")) { return true; } else { return false; } } //是否有汉字 public static bool IsChina(string CString) { bool BoolValue = false; for (int i = 0; i < CString.Length; i++) { if (!(Convert.ToInt32(Convert.ToChar(CString.Substring(i, 1))) < Convert.ToInt32(Convert.ToChar(128)))) { BoolValue = true; break; } } return BoolValue; } /// <summary> /// 取单个字符的拼音声母 /// </summary> /// <param name="c">要转换的单个汉字</param> /// <returns>拼音声母</returns> public static string GetSpellChar(string c) { byte[] array = new byte[2]; array = System.Text.Encoding.Default.GetBytes(c); int i = (short)(array[0] - '0') * 256 + ((short)(array[1] - '0')); if (i < 0xB0A1) return "*"; if (i < 0xB0C5) return "a"; if (i < 0xB2C1) return "b"; if (i < 0xB4EE) return "c"; if (i < 0xB6EA) return "d"; if (i < 0xB7A2) return "e"; if (i < 0xB8C1) return "f"; if (i < 0xB9FE) return "g"; if (i < 0xBBF7) return "h"; if (i < 0xBFA6) return "j"; if (i < 0xC0AC) return "k"; if (i < 0xC2E8) return "l"; if (i < 0xC4C3) return "m"; if (i < 0xC5B6) return "n"; if (i < 0xC5BE) return "o"; if (i < 0xC6DA) return "p"; if (i < 0xC8BB) return "q"; if (i < 0xC8F6) return "r"; if (i < 0xCBFA) return "s"; if (i < 0xCDDA) return "t"; if (i < 0xCEF4) return "w"; if (i < 0xD1B9) return "x"; if (i < 0xD4D1) return "y"; if (i < 0xD7FA) return "z"; return "*"; } #endregion #region 汉字转拼方法2 private static Hashtable _Phrase; /// <summary> /// 设置或获取包含列外词组读音的键/值对的组合。 /// </summary> public static Hashtable Phrase { get { if (_Phrase == null) { _Phrase = new Hashtable(); _Phrase.Add("圳", "Zhen"); _Phrase.Add("什么", "ShenMe"); _Phrase.Add("晖", "Hui"); _Phrase.Add("孑", "Jie"); _Phrase.Add("韬", "TAO"); } return _Phrase; } set { _Phrase = value; } } #region 定义编码 private static int[] pyvalue = new int[] { -20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032, -20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728, -19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261, -19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961, -18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490, -18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988, -17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692, -17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733, -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419, -16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959, -15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631, -15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180, -15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941, -14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857, -14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353, -14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094, -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831, -13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329, -13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860, -12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300, -12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358, -11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014, -10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309, -10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254 }; private static string[] pystr = new string[] { "a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian", "biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan" , "chang", "chao", "che", "chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong" , "cou", "cu", "cuan", "cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du", "duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga" , "gai", "gan", "gang", "gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang", "hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian", "jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken", "keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng", "li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai", "man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai", "nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan", "nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu", "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re", "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha", "shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun", "shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao", "tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi", "xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi", "yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha", "zhai" , "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui", "zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo" }; #endregion #region 获取汉字拼音 /// <summary> /// 获取汉字拼音 /// </summary> /// <param name="chsstr">汉字字符串</param> /// <returns>拼音</returns> public static string GetSpellByChinese(string _chineseString) { _chineseString = RepacePinyinChar(_chineseString); string strRet = string.Empty; // 例外词组 foreach (DictionaryEntry de in Phrase) { _chineseString = _chineseString.Replace(de.Key.ToString(), de.Value.ToString()); } char[] ArrChar = _chineseString.ToCharArray(); string strPY = string.Empty; foreach (char c in ArrChar) { strPY = GetSingleSpellByChinese(c.ToString()); if (strPY.ToUpper() == "ZUO" || strPY.ToUpper() == "") { byte[] chinase = null; strPY = chs2py.convert(c.ToString(), out chinase); if (strPY == "") { strPY = chs2py.FindPinYin(c.ToString(), out chinase); } //将首字母转为大写 if (strPY.Length > 1) { strPY = strPY.Substring(0, 1).ToUpper() + strPY.Substring(1); } } strRet += strPY; } return strRet; } #endregion #region 获取汉字拼音首字母 /// <summary> /// 获取汉字拼音首字母 /// </summary> /// <param name="chsstr">指定汉字</param> /// <returns>拼音首字母</returns> public static string GetHeadSpellByChinese(string _chineseString) { string strRet = string.Empty; char[] ArrChar = _chineseString.ToCharArray(); foreach (char c in ArrChar) { strRet += GetHeadSingleSpellByChinese(c.ToString()); } return strRet; } #endregion #region 获取单个汉字拼音 /// <summary> /// 获取单个汉字拼音 /// </summary> /// <param name="SingleChs">单个汉字</param> /// <returns>拼音</returns> private static string GetSingleSpellByChinese(string _singleChineseString) { byte[] array = Encoding.Default.GetBytes(_singleChineseString); int iAsc; string strRtn = string.Empty; try { iAsc = (short)(array[0]) * 256 + (short)(array[1]) - 65536; } catch { iAsc = 1; } if (iAsc > 0 && iAsc < 160) return _singleChineseString; for (int i = (pyvalue.Length - 1); i >= 0; i--) { if (pyvalue[i] <= iAsc) { strRtn = pystr[i]; break; } } //将首字母转为大写 if (strRtn.Length > 1) { strRtn = strRtn.Substring(0, 1).ToUpper() + strRtn.Substring(1); } return strRtn; } #endregion #region 获取单个汉字的首字母 /// <summary> /// 获取单个汉字的首字母 /// </summary> /// <returns></returns> private static string GetHeadSingleSpellByChinese(string _singleChineseString) { // 例外词组 foreach (DictionaryEntry de in Phrase) { _singleChineseString = _singleChineseString.Replace(de.Key.ToString(), de.Value.ToString()); } return GetSingleSpellByChinese(_singleChineseString).Substring(0, 1); } #endregion #region 获取汉字拼音(第一个汉字只有首字母) /// <summary> /// 获取汉字拼音(第一个汉字只有首字母) /// </summary> /// <param name="_chineseString"></param> /// <returns></returns> public static string GetAbSpellByChinese(string _chineseString) { string strRet = string.Empty; // 例外词组 foreach (DictionaryEntry de in Phrase) { _chineseString = _chineseString.Replace(de.Key.ToString(), de.Value.ToString()); } char[] ArrChar = _chineseString.ToCharArray(); for (int i = 0; i < ArrChar.Length; i++) { if (i == 0) { strRet += GetHeadSingleSpellByChinese(ArrChar[i].ToString()); } else { strRet += GetSingleSpellByChinese(ArrChar[i].ToString()); } } return strRet; } #endregion #endregion } public class chs2py { public chs2py() { // // TODO: 在此处添加构造函数逻辑 // } /// <summary> ///将汉字转换成为拼音及航信支持的汉字编码格式 /// </summary> #region 变量 private static int[] pyvalue = new int[]{-20319,-20317,-20304,-20295,-20292,-20283,-20265,-20257,-20242,-20230,-20051,-20036,-20032,-20026, -20002,-19990,-19986,-19982,-19976,-19805,-19784,-19775,-19774,-19763,-19756,-19751,-19746,-19741,-19739,-19728, -19725,-19715,-19540,-19531,-19525,-19515,-19500,-19484,-19479,-19467,-19289,-19288,-19281,-19275,-19270,-19263, -19261,-19249,-19243,-19242,-19238,-19235,-19227,-19224,-19218,-19212,-19038,-19023,-19018,-19006,-19003,-18996, -18977,-18961,-18952,-18783,-18774,-18773,-18763,-18756,-18741,-18735,-18731,-18722,-18710,-18697,-18696,-18526, -18518,-18501,-18490,-18478,-18463,-18448,-18447,-18446,-18239,-18237,-18231,-18220,-18211,-18201,-18184,-18183, -18181,-18012,-17997,-17988,-17970,-17964,-17961,-17950,-17947,-17931,-17928,-17922,-17759,-17752,-17733,-17730, -17721,-17703,-17701,-17697,-17692,-17683,-17676,-17496,-17487,-17482,-17468,-17454,-17433,-17427,-17417,-17202, -17185,-16983,-16970,-16942,-16915,-16733,-16708,-16706,-16689,-16664,-16657,-16647,-16474,-16470,-16465,-16459, -16452,-16448,-16433,-16429,-16427,-16423,-16419,-16412,-16407,-16403,-16401,-16393,-16220,-16216,-16212,-16205, -16202,-16187,-16180,-16171,-16169,-16158,-16155,-15959,-15958,-15944,-15933,-15920,-15915,-15903,-15889,-15878, -15707,-15701,-15681,-15667,-15661,-15659,-15652,-15640,-15631,-15625,-15454,-15448,-15436,-15435,-15419,-15416, -15408,-15394,-15385,-15377,-15375,-15369,-15363,-15362,-15183,-15180,-15165,-15158,-15153,-15150,-15149,-15144, -15143,-15141,-15140,-15139,-15128,-15121,-15119,-15117,-15110,-15109,-14941,-14937,-14933,-14930,-14929,-14928, -14926,-14922,-14921,-14914,-14908,-14902,-14894,-14889,-14882,-14873,-14871,-14857,-14678,-14674,-14670,-14668, -14663,-14654,-14645,-14630,-14594,-14429,-14407,-14399,-14384,-14379,-14368,-14355,-14353,-14345,-14170,-14159, -14151,-14149,-14145,-14140,-14137,-14135,-14125,-14123,-14122,-14112,-14109,-14099,-14097,-14094,-14092,-14090, -14087,-14083,-13917,-13914,-13910,-13907,-13906,-13905,-13896,-13894,-13878,-13870,-13859,-13847,-13831,-13658, -13611,-13601,-13406,-13404,-13400,-13398,-13395,-13391,-13387,-13383,-13367,-13359,-13356,-13343,-13340,-13329, -13326,-13318,-13147,-13138,-13120,-13107,-13096,-13095,-13091,-13076,-13068,-13063,-13060,-12888,-12875,-12871, -12860,-12858,-12852,-12849,-12838,-12831,-12829,-12812,-12802,-12607,-12597,-12594,-12585,-12556,-12359,-12346, -12320,-12300,-12120,-12099,-12089,-12074,-12067,-12058,-12039,-11867,-11861,-11847,-11831,-11798,-11781,-11604, -11589,-11536,-11358,-11340,-11339,-11324,-11303,-11097,-11077,-11067,-11055,-11052,-11045,-11041,-11038,-11024, -11020,-11019,-11018,-11014,-10838,-10832,-10815,-10800,-10790,-10780,-10764,-10587,-10544,-10533,-10519,-10331, -10329,-10328,-10322,-10315,-10309,-10307,-10296,-10281,-10274,-10270,-10262,-10260,-10256,-10254}; private static string[] pystr = new string[]{"a","ai","an","ang","ao","ba","bai","ban","bang","bao","bei","ben","beng","bi","bian","biao", "bie","bin","bing","bo","bu","ca","cai","can","cang","cao","ce","ceng","cha","chai","chan","chang","chao","che","chen", "cheng","chi","chong","chou","chu","chuai","chuan","chuang","chui","chun","chuo","ci","cong","cou","cu","cuan","cui", "cun","cuo","da","dai","dan","dang","dao","de","deng","di","dian","diao","die","ding","diu","dong","dou","du","duan", "dui","dun","duo","e","en","er","fa","fan","fang","fei","fen","feng","fo","fou","fu","ga","gai","gan","gang","gao", "ge","gei","gen","geng","gong","gou","gu","gua","guai","guan","guang","gui","gun","guo","ha","hai","han","hang", "hao","he","hei","hen","heng","hong","hou","hu","hua","huai","huan","huang","hui","hun","huo","ji","jia","jian", "jiang","jiao","jie","jin","jing","jiong","jiu","ju","juan","jue","jun","ka","kai","kan","kang","kao","ke","ken", "keng","kong","kou","ku","kua","kuai","kuan","kuang","kui","kun","kuo","la","lai","lan","lang","lao","le","lei", "leng","li","lia","lian","liang","liao","lie","lin","ling","liu","long","lou","lu","lv","luan","lue","lun","luo", "ma","mai","man","mang","mao","me","mei","men","meng","mi","mian","miao","mie","min","ming","miu","mo","mou","mu", "na","nai","nan","nang","nao","ne","nei","nen","neng","ni","nian","niang","niao","nie","nin","ning","niu","nong", "nu","nv","nuan","nue","nuo","o","ou","pa","pai","pan","pang","pao","pei","pen","peng","pi","pian","piao","pie", "pin","ping","po","pu","qi","qia","qian","qiang","qiao","qie","qin","qing","qiong","qiu","qu","quan","que","qun", "ran","rang","rao","re","ren","reng","ri","rong","rou","ru","ruan","rui","run","ruo","sa","sai","san","sang", "sao","se","sen","seng","sha","shai","shan","shang","shao","she","shen","sheng","shi","shou","shu","shua", "shuai","shuan","shuang","shui","shun","shuo","si","song","sou","su","suan","sui","sun","suo","ta","tai", "tan","tang","tao","te","teng","ti","tian","tiao","tie","ting","tong","tou","tu","tuan","tui","tun","tuo", "wa","wai","wan","wang","wei","wen","weng","wo","wu","xi","xia","xian","xiang","xiao","xie","xin","xing", "xiong","xiu","xu","xuan","xue","xun","ya","yan","yang","yao","ye","yi","yin","ying","yo","yong","you", "yu","yuan","yue","yun","za","zai","zan","zang","zao","ze","zei","zen","zeng","zha","zhai","zhan","zhang", "zhao","zhe","zhen","zheng","zhi","zhong","zhou","zhu","zhua","zhuai","zhuan","zhuang","zhui","zhun","zhuo", "zi","zong","zou","zu","zuan","zui","zun","zuo"}; public static List<string> pinyinList = null; #endregion 变量 #region 重新加载拼音文件 public static List<string> ReadPinYin() { List<string> strList = new List<string>(); string filename = "pinyin.dat"; if (File.Exists(filename)) { StreamReader reader = new StreamReader(filename, System.Text.Encoding.Default); string[] strArray = reader.ReadToEnd().Split(new string[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); reader.Close(); strList.AddRange(strArray); } return strList; } /// <summary> /// 查找汉字 /// </summary> /// <param name="chrstr"></param> /// <param name="ChineseBuf"></param> /// <returns></returns> public static string FindPinYin(string HanziChar, out byte[] ChineseBuf) { pinyinList = ReadPinYin(); ChineseBuf = null; string strReturn = string.Empty; string strLine = pinyinList.Where(p => p.StartsWith(HanziChar)).FirstOrDefault(); if (!string.IsNullOrEmpty(strLine)) { //隘 ai 0x25 0x22 string[] sl = strLine.Trim().Split(new char[1] { ' ' }); strReturn = sl[1]; if (sl.Length == 4) { if (ChineseBuf == null) { ChineseBuf = new byte[2]; } ChineseBuf[0] = GetByteFromString(sl[2]); ChineseBuf[1] = GetByteFromString(sl[3]); } else if (sl.Length > 4) { if (ChineseBuf == null) { ChineseBuf = new byte[4]; } ChineseBuf[0] = GetByteFromString(sl[2]); ChineseBuf[1] = GetByteFromString(sl[3]); ChineseBuf[2] = GetByteFromString(sl[4]); ChineseBuf[3] = GetByteFromString(sl[5]); } } return strReturn; } public static void ReloadPinYinFile() { try { pinyinList = ReadPinYin(); } catch (Exception ex) { LogText.LogWrite("重新加载拼音文件出错,错误信息:" + ex.Message, "PinYinErr"); } } #endregion 重新加载拼音文件 #region 十六进制转换成字符串 //把0x20 转换为字符串 “0x20” public static string GetStringFromByte(byte buf) { string strResult = "0X"; int tmp1 = buf / 16; int tmp2 = buf % 16; switch (tmp1) { case 10: strResult += "A"; break; case 11: strResult += "B"; break; case 12: strResult += "C"; break; case 13: strResult += "D"; break; case 14: strResult += "E"; break; case 15: strResult += "F"; break; default: strResult += Convert.ToString(tmp1); break; } switch (tmp2) { case 10: strResult += "A"; break; case 11: strResult += "B"; break; case 12: strResult += "C"; break; case 13: strResult += "D"; break; case 14: strResult += "E"; break; case 15: strResult += "F"; break; default: strResult += Convert.ToString(tmp2); break; } return strResult; } #endregion 十六进制转换成字符串 #region 字符串转换成十六进制 //把字符串 “0x20” 转换为 0x20 public static byte GetByteFromString(string str) { string tmpstr = str.Trim().ToUpper(); if (tmpstr.Length != 4) return 0x00; string strbuf = tmpstr.Substring(2, 1); byte buf = 0x00; switch (strbuf) { case "A": buf += (byte)(10 * 16); break; case "B": buf += (byte)(11 * 16); break; case "C": buf += (byte)(12 * 16); break; case "D": buf += (byte)(13 * 16); break; case "E": buf += (byte)(14 * 16); break; case "F": buf += (byte)(15 * 16); break; default: buf += (byte)(Convert.ToInt32(strbuf) * 16); break; } strbuf = tmpstr.Substring(3, 1); switch (strbuf) { case "A": buf += (byte)(10); break; case "B": buf += (byte)(11); break; case "C": buf += (byte)(12); break; case "D": buf += (byte)(13); break; case "E": buf += (byte)(14); break; case "F": buf += (byte)(15); break; default: buf += (byte)(Convert.ToInt32(strbuf)); break; } return buf; } #endregion 字符串转换成十六进制 #region 汉字编码转换成对应汉字 //通过汉字编码取得汉字 public static string GetHanZi(byte[] ChineseBuf) { string tmpbuf = ""; try { for (int i = 0; i < ChineseBuf.Length; i++) { if (tmpbuf == "") { tmpbuf = GetStringFromByte(ChineseBuf[i]); } else { tmpbuf += " " + GetStringFromByte(ChineseBuf[i]); } } if (pinyinList == null) { pinyinList = ReadPinYin(); } //先从汉字配置文件中查找是否存在,如果不存在则继续下面的流程 string tmpstr = ""; for (int i = 0; i < pinyinList.Count; i++) { tmpstr = pinyinList[i]; if (tmpstr.ToUpper().IndexOf(tmpbuf) != -1) { string[] sl = tmpstr.Split(new char[1] { ' ' }); return sl[0]; } } } catch (Exception ex) { LogText.LogWrite("汉字编码转换成对应汉字,错误信息:" + ex.Message, "PinYinErr"); } return ""; } #endregion 汉字编码转换成对应汉字 #region 根据汉字获取汉字拼音及汉字编码 /// <summary> /// 根据汉字获取汉字拼音及汉字编码 /// </summary> /// <param name="chrstr">汉字</param> /// <param name="ChineseBuf">汉字编码</param> /// <returns>汉字的拼音</returns> public static string convert(string chrstr, out byte[] ChineseBuf) { byte[] array = new byte[2]; string returnstr = ""; int chrasc = 0; int i1 = 0; int i2 = 0; ChineseBuf = null; try { if (pinyinList == null) { pinyinList = ReadPinYin(); } //先从汉字配置文件中查找是否存在,如果不存在则继续下面的流程 string tmpstr = ""; for (int i = 0; i < pinyinList.Count; i++) { tmpstr = pinyinList[i]; if (tmpstr.IndexOf(chrstr) != -1) { string[] sl = tmpstr.Trim().Split(new char[1] { ' ' }); int count = 0; string strReturn = ""; for (int j = 0; j < sl.Length; j++) { if (sl[j].Trim() == "") continue; switch (count) { //汉字 case 0: break; //拼音 case 1: strReturn = sl[j]; break; } count++; if (sl.Length == 4) { if (ChineseBuf == null) { ChineseBuf = new byte[2]; } ChineseBuf[0] = GetByteFromString(sl[2]); ChineseBuf[1] = GetByteFromString(sl[3]); } else if (sl.Length > 4) { if (ChineseBuf == null) { ChineseBuf = new byte[4]; } ChineseBuf[0] = GetByteFromString(sl[2]); ChineseBuf[1] = GetByteFromString(sl[3]); ChineseBuf[2] = GetByteFromString(sl[4]); ChineseBuf[3] = GetByteFromString(sl[5]); } } return strReturn; } } char[] nowchar = chrstr.ToCharArray(); for (int j = 0; j < nowchar.Length; j++) { array = System.Text.Encoding.Default.GetBytes(nowchar[j].ToString()); i1 = (short)(array[0]); i2 = (short)(array[1]); chrasc = i1 * 256 + i2 - 65536; if (chrasc > 0 && chrasc < 160) { returnstr += nowchar[j]; } else { for (int i = (pyvalue.Length - 1); i >= 0; i--) { if (pyvalue[i] <= chrasc) { returnstr += pystr[i]; break; } } } } } catch (Exception ex) { LogText.LogWrite("根据汉字获取汉字拼音及汉字编码,错误信息:" + ex.Message, "PinYinErr"); } return returnstr; } #endregion 根据汉字获取汉字拼音及汉字编码 } }
using System; using System.Globalization; public class Program { public static void Main() { var photoNumber = int.Parse(Console.ReadLine()); var photoDay = int.Parse(Console.ReadLine()); var photoMonth = int.Parse(Console.ReadLine()); var photoYear = int.Parse(Console.ReadLine()); var photoHour = int.Parse(Console.ReadLine()); var photoMinutes = int.Parse(Console.ReadLine()); var photoSize = long.Parse(Console.ReadLine()); var photoWidth = int.Parse(Console.ReadLine()); var photoHeight = int.Parse(Console.ReadLine()); var name = $"DSC_{photoNumber:D4}.jpg"; var dateTaken = DateTime.ParseExact($"{photoDay:D2}/{photoMonth:D2}/{photoYear} {photoHour:D2}:{photoMinutes:D2}", "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy HH:mm"); var photoHumanSize = GetReadableFileSize(photoSize); var photoScape = photoWidth / (double)photoHeight; var photoScapey = string.Empty; if (photoScape > 1) { photoScapey = "landscape"; } else if (photoScape == 1) { photoScapey = "square"; } else { photoScapey = "portrait"; } Console.WriteLine($"Name: {name}"); Console.WriteLine($"Date Taken: {dateTaken}"); Console.WriteLine($"Size: {photoHumanSize}"); Console.WriteLine($"Resolution: {photoWidth}x{photoHeight} ({photoScapey})"); } private static string GetReadableFileSize(long photoSize) { var humanReadableFormatSize = string.Empty; var formatExtensions = new string[] { "B", "KB", "MB", "GB", "TB", "PB" }; var indexer = 0; var currNumber = (double)photoSize; while (true) { if (currNumber > 1000) { currNumber /= 1000; indexer++; } else { humanReadableFormatSize = formatExtensions[indexer]; break; } } return(currNumber + humanReadableFormatSize); } }
using LuaInterface; using SLua; using System; using UnityEngine; public class Lua_UnityEngine_LocationInfo : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { LocationInfo locationInfo = default(LocationInfo); LuaObject.pushValue(l, true); LuaObject.pushValue(l, locationInfo); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_latitude(IntPtr l) { int result; try { LocationInfo locationInfo; LuaObject.checkValueType<LocationInfo>(l, 1, out locationInfo); LuaObject.pushValue(l, true); LuaObject.pushValue(l, locationInfo.get_latitude()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_longitude(IntPtr l) { int result; try { LocationInfo locationInfo; LuaObject.checkValueType<LocationInfo>(l, 1, out locationInfo); LuaObject.pushValue(l, true); LuaObject.pushValue(l, locationInfo.get_longitude()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_altitude(IntPtr l) { int result; try { LocationInfo locationInfo; LuaObject.checkValueType<LocationInfo>(l, 1, out locationInfo); LuaObject.pushValue(l, true); LuaObject.pushValue(l, locationInfo.get_altitude()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_horizontalAccuracy(IntPtr l) { int result; try { LocationInfo locationInfo; LuaObject.checkValueType<LocationInfo>(l, 1, out locationInfo); LuaObject.pushValue(l, true); LuaObject.pushValue(l, locationInfo.get_horizontalAccuracy()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_verticalAccuracy(IntPtr l) { int result; try { LocationInfo locationInfo; LuaObject.checkValueType<LocationInfo>(l, 1, out locationInfo); LuaObject.pushValue(l, true); LuaObject.pushValue(l, locationInfo.get_verticalAccuracy()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_timestamp(IntPtr l) { int result; try { LocationInfo locationInfo; LuaObject.checkValueType<LocationInfo>(l, 1, out locationInfo); LuaObject.pushValue(l, true); LuaObject.pushValue(l, locationInfo.get_timestamp()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.LocationInfo"); LuaObject.addMember(l, "latitude", new LuaCSFunction(Lua_UnityEngine_LocationInfo.get_latitude), null, true); LuaObject.addMember(l, "longitude", new LuaCSFunction(Lua_UnityEngine_LocationInfo.get_longitude), null, true); LuaObject.addMember(l, "altitude", new LuaCSFunction(Lua_UnityEngine_LocationInfo.get_altitude), null, true); LuaObject.addMember(l, "horizontalAccuracy", new LuaCSFunction(Lua_UnityEngine_LocationInfo.get_horizontalAccuracy), null, true); LuaObject.addMember(l, "verticalAccuracy", new LuaCSFunction(Lua_UnityEngine_LocationInfo.get_verticalAccuracy), null, true); LuaObject.addMember(l, "timestamp", new LuaCSFunction(Lua_UnityEngine_LocationInfo.get_timestamp), null, true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_LocationInfo.constructor), typeof(LocationInfo), typeof(ValueType)); } }
using System.Text; using System; using System.Collections.Generic; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.Net.Http; using System.Drawing; using System.Collections.ObjectModel; using System.Xml; using System.ComponentModel; using System.Reflection; namespace LinnworksAPI { public class BookedReturnsExchangeOrder { public Guid pkOrderID; public Int32 nOrderId; public String ReferenceNum; public String SecondaryReference; public String cFullName; public DateTime ReturnDate; } }
using CustomerAgenda.Business.Models; using System; using System.Collections.Generic; namespace CustomerAgenda.Business.Interfaces { public interface IRepository<TEntity> : IDisposable where TEntity : Entity { void Insert(TEntity entity); TEntity Read(Guid id); void Update(TEntity entity); void Delete(Guid id); IEnumerable<TEntity> List(); int SaveChanges(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { public GameObject virus1, virus2; public static bool IsVirus1Playing=false; private int c = 0; // Update is called once per frame /* void Update() { if (BattleMachine.IsEnemyChoosing) { if (c % 2 == 0) { Debug.Log("Enemy 1 Selected"); Virus1 virus1Controller = virus1.GetComponent<Virus1>(); IsVirus1Playing = true; BattleMachine.IsEnemyChoosing = false; } else { Debug.Log("Enemy 2 Selected"); Virus1 virus2Controller = virus2.GetComponent<Virus1>(); IsVirus1Playing = true; BattleMachine.IsEnemyChoosing = false; } } c++; }*/ }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Brick : MonoBehaviour { private int life; public enum Type {red, yellow, green, blue}; public Type type; private Material mat; private void Awake() { // Different brick types need a different number of hits to get destroyed switch(type) { case Type.red: { life = 4; break; } case Type.yellow: { life = 3; break; } case Type.green: { life = 2; break; } case Type.blue: { life = 1; break; } default: break; } mat = GetComponent<Renderer>().material; SetColor(); } // Called every time the brick gets hit public void Break() { life -= 1; SetColor(); if (life == 0) { Manager.Instance.bricks.Remove(this.gameObject); Destroy(this.gameObject); } } // Color changes according to 'life' points private void SetColor() { if (life == 4) mat.color = Manager.Instance.red.color; if (life == 3) mat.color = Manager.Instance.yellow.color; if (life == 2) mat.color = Manager.Instance.green.color; if (life == 1) mat.color = Manager.Instance.blue.color; } }
using LuaInterface; using RO; using SLua; using System; using UnityEngine; public class Lua_RO_InputInfo : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { InputInfo o = new InputInfo(); LuaObject.pushValue(l, true); LuaObject.pushValue(l, o); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_Global(IntPtr l) { int result; try { LuaObject.pushValue(l, true); LuaObject.pushValue(l, InputInfo.Global); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_touchEventType(IntPtr l) { int result; try { InputInfo inputInfo = (InputInfo)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushEnum(l, (int)inputInfo.touchEventType); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_touchEventType(IntPtr l) { int result; try { InputInfo inputInfo = (InputInfo)LuaObject.checkSelf(l); TouchEventType touchEventType; LuaObject.checkEnum<TouchEventType>(l, 2, out touchEventType); inputInfo.touchEventType = touchEventType; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_pointerID(IntPtr l) { int result; try { InputInfo inputInfo = (InputInfo)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, inputInfo.pointerID); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_pointerID(IntPtr l) { int result; try { InputInfo inputInfo = (InputInfo)LuaObject.checkSelf(l); int pointerID; LuaObject.checkType(l, 2, out pointerID); inputInfo.pointerID = pointerID; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_touchPoint(IntPtr l) { int result; try { InputInfo inputInfo = (InputInfo)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, inputInfo.touchPoint); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_touchPoint(IntPtr l) { int result; try { InputInfo inputInfo = (InputInfo)LuaObject.checkSelf(l); Vector3 touchPoint; LuaObject.checkType(l, 2, out touchPoint); inputInfo.touchPoint = touchPoint; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_beginOnUI(IntPtr l) { int result; try { InputInfo inputInfo = (InputInfo)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, inputInfo.beginOnUI); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_beginOnUI(IntPtr l) { int result; try { InputInfo inputInfo = (InputInfo)LuaObject.checkSelf(l); bool beginOnUI; LuaObject.checkType(l, 2, out beginOnUI); inputInfo.beginOnUI = beginOnUI; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_overUI(IntPtr l) { int result; try { InputInfo inputInfo = (InputInfo)LuaObject.checkSelf(l); LuaObject.pushValue(l, true); LuaObject.pushValue(l, inputInfo.overUI); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int set_overUI(IntPtr l) { int result; try { InputInfo inputInfo = (InputInfo)LuaObject.checkSelf(l); bool overUI; LuaObject.checkType(l, 2, out overUI); inputInfo.overUI = overUI; LuaObject.pushValue(l, true); result = 1; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "RO.InputInfo"); LuaObject.addMember(l, "Global", new LuaCSFunction(Lua_RO_InputInfo.get_Global), null, false); LuaObject.addMember(l, "touchEventType", new LuaCSFunction(Lua_RO_InputInfo.get_touchEventType), new LuaCSFunction(Lua_RO_InputInfo.set_touchEventType), true); LuaObject.addMember(l, "pointerID", new LuaCSFunction(Lua_RO_InputInfo.get_pointerID), new LuaCSFunction(Lua_RO_InputInfo.set_pointerID), true); LuaObject.addMember(l, "touchPoint", new LuaCSFunction(Lua_RO_InputInfo.get_touchPoint), new LuaCSFunction(Lua_RO_InputInfo.set_touchPoint), true); LuaObject.addMember(l, "beginOnUI", new LuaCSFunction(Lua_RO_InputInfo.get_beginOnUI), new LuaCSFunction(Lua_RO_InputInfo.set_beginOnUI), true); LuaObject.addMember(l, "overUI", new LuaCSFunction(Lua_RO_InputInfo.get_overUI), new LuaCSFunction(Lua_RO_InputInfo.set_overUI), true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_RO_InputInfo.constructor), typeof(InputInfo)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace лаба_7 { abstract partial class Plant { public virtual void rost() { } int hidth; string vid; DateTime age; } }
// <copyright file="StatusToColorConverter.cs" company="Soloplan GmbH"> // Copyright (c) Soloplan GmbH. All rights reserved. // Licensed under the MIT License. See License-file in the project root for license information. // </copyright> namespace Soloplan.WhatsON.GUI.Common.Converters { using System; using System.Globalization; using System.Windows.Data; using System.Windows.Media; using Soloplan.WhatsON.GUI.Common.ConnectorTreeView; using Soloplan.WhatsON.Model; public class StatusToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is StatusViewModel status) { Color color = GetColor(status.State); return new SolidColorBrush(color); } if (value is ObservationState state) { return new SolidColorBrush(GetColor(state)); } return new SolidColorBrush(System.Windows.Media.Colors.White); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } private static Color GetColor(ObservationState state) { switch (state) { case ObservationState.Unstable: return System.Windows.Media.Colors.Orange; break; case ObservationState.Failure: return Color.FromRgb(201, 42, 60); break; case ObservationState.Success: return Color.FromRgb(66, 171, 20); break; case ObservationState.Running: return System.Windows.Media.Colors.DarkCyan; break; default: return Color.FromRgb(120, 144, 156); break; } } } }
using OzzIdentity.Resources; using System.ComponentModel.DataAnnotations; namespace OzzIdentity.Models { public class LoginViewModel { [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "RequiredEmail")] [Display(ResourceType = typeof(TitleStrings), Name = "UserName")] public string UserName { get; set; } [DataType(DataType.Password)] [Required(ErrorMessageResourceType = typeof(ErrorStrings), ErrorMessageResourceName = "RequiredPassword")] [Display(ResourceType = typeof(TitleStrings), Name = "Password")] public string Password { get; set; } [Display(ResourceType = typeof(TitleStrings), Name = "RememberMe")] public bool RememberMe { get; set; } } }
using System; using System.Collections; using Server.Items; using Server.Mobiles; using Server.Misc; using Server.Network; namespace Server.Items { public class LeatherWolfDeed: Item { public bool m_AllowConstruction; public Timer m_ConstructionTimer; private DateTime m_End; [CommandProperty( AccessLevel.GameMaster )] public bool AllowConstruction { get{ return m_AllowConstruction; } set{ m_AllowConstruction = value; } } [Constructable] public LeatherWolfDeed() : base( 0x14F0 ) { Weight = 0.01; Name = "a leather wolf deed"; AllowConstruction = false; m_ConstructionTimer = new ConstructionTimer( this, TimeSpan.FromDays( 0.0 ) ); m_ConstructionTimer.Start(); m_End = DateTime.Now + TimeSpan.FromDays( 0.0 ); } public LeatherWolfDeed( Serial serial ) : base ( serial ) { } public override void OnDoubleClick( Mobile from ) { if ( !IsChildOf( from.Backpack ) ) { from.SendMessage( "You must have the deed in your backpack to use it." ); } else if ( this.AllowConstruction == true ) { this.Delete(); from.SendMessage( "You have constructed a leather wolf!!" ); CraftedLeatherWolf lwolf = new CraftedLeatherWolf(); lwolf.Map = from.Map; lwolf.Location = from.Location; lwolf.Controlled = true; lwolf.ControlMaster = from; lwolf.IsBonded = true; } else { from.SendMessage( "This can not be constructed yet, please wait...." ); } } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); writer.WriteDeltaTime( m_End ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 1: { m_End = reader.ReadDeltaTime(); m_ConstructionTimer = new ConstructionTimer( this, m_End - DateTime.Now ); m_ConstructionTimer.Start(); break; } case 0: { TimeSpan duration = TimeSpan.FromDays( 0.0 ); m_ConstructionTimer = new ConstructionTimer( this, duration ); m_ConstructionTimer.Start(); m_End = DateTime.Now + duration; break; } } } private class ConstructionTimer : Timer { private LeatherWolfDeed de; private int cnt = 0; public ConstructionTimer( LeatherWolfDeed owner, TimeSpan duration ) : base( duration ) { de = owner; } protected override void OnTick() { cnt += 1; if ( cnt == 1 ) { de.AllowConstruction = true; } } } } }
using System; using System.Collections.Generic; using System.Linq; using Shunxi.Business.Models.devices; using Shunxi.Common.Log; namespace Shunxi.Business.Logic.Cultivations { public abstract class BaseCultivation { public BaseCultivation(Pump pump) { Device = pump; } public Pump Device { get; set; } #region 重构 public abstract void CalcSchedules(); //获取下一次运行的时间、速度、体积 public abstract Tuple<DateTime, double, double> GetNextRunParams(bool isFirst); //点击开始后 先计算并缓存所有的排期 //点击暂停后记录暂停时间A 重新开始后记录开始时间B 将排期中大于A的数据增加B-A public IList<DateTime> Schedules = new List<DateTime>(); public virtual void AdjustTimeForPause(DateTime stopTime) { LogFactory.Create().Info($"AdjustTimeForPause stopTime {stopTime:yyyy-MM-dd HH:mm:ss}"); var now = DateTime.Now; var span = now - stopTime;//暂停时长 for (var i = 0; i < Schedules.Count; i++) { //暂停只影响还未执行的排期 if (Schedules[i] > stopTime) { Schedules[i] = Schedules[i].Add(span); } } } public virtual void AdjustStartTimeWhenFirstRun(TimeSpan span) { LogFactory.Create().Info($"Device{Device.DeviceId} AdjustStartTimeWhenFirstRun {span.TotalMinutes:##.###} minutes"); for (var i = 0; i < Schedules.Count; i++) { Schedules[i] = Schedules[i].Add(span); } } public bool hasNearStartTime(DateTime now) { return Schedules.Any(each => Math.Abs((each -now).TotalSeconds) < 5); } #endregion } }
using System; using System.ComponentModel.DataAnnotations; using DataAnnotationsExtensions; namespace SalaryUpdate.Models { public class ReturnedSalary { public string EmployeeId { get; set; } public int EmployerId { get; set; } [Display(Name = "Total Salary"), Range(0.01, 1000000, ErrorMessage = "{0} must be greater than $0.00 and less than $1,000,000.00!")] public decimal NewTotalSalary { get; set; } [Min(0)] public decimal NewBasicCash { get; set; } [Min(0)] public decimal NewMealsProvided { get; set; } [Min(0)] public decimal NewCashMealAllowance { get; set; } [Min(0)] public decimal NewCashCellphoneAllowance { get; set; } [Display(Name = "Hours"), Range(20.01, 60, ErrorMessage = "{0} must be greater than 20 and less than {2}!")] public decimal NewHoursPerWeek { get; set; } public bool Exported { get; set; } public DateTime DateCreated { get; set; } public DateTime DateModified { get; set; } public DateTime? DateExported { get; set; } } }
using Common; using Sdbs.Wms.Controls.Pager; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Wms.Controls.Pager; using WmsSDK; using WmsSDK.Model; using WmsSDK.Request; using WmsSDK.Response; namespace WmsApp { public partial class PackageTaskForm : TabWindow { private PaginatorDTO paginator; private SortableBindingList<PackTask> sortList = null; private IWMSClient client = null; public PackageTaskForm() { InitializeComponent(); client = new DefalutWMSClient(); } private void PackageTaskForm_Load(object sender, EventArgs e) { try { dtBegin.Value = DateTime.Today.AddDays(2).AddDays(-1); // dtEnd.Value = DateTime.Today.AddDays(1).AddSeconds(-1); this.dataGridView1.AutoGenerateColumns = false; paginator = new PaginatorDTO { PageNo = 1, PageSize = 100 }; cbStatus.SelectedIndex = 0; BindDgv(); } catch (Exception ex) { LogHelper.Log("PackageTaskForm_Load" + ex.Message); MessageBox.Show(ex.Message); } } private void BindDgv() { PackTaskRequest request = new PackTaskRequest(); request.PageIndex = paginator.PageNo; request.PageSize = paginator.PageSize; request.startTime = dtBegin.Value.ToString("yyyy-MM-dd HH:mm:ss"); request.endTime = dtBegin.Value.ToString("yyyy-MM-dd 23:59:59"); request.partnerCode = UserInfo.PartnerCode; request.skuCode = tbName.Text.Trim(); request.packTaskType = 10; if (cbStatus.SelectedIndex == 0) { request.status = null; } if (cbStatus.SelectedIndex == 1) { request.status = 0; } if (cbStatus.SelectedIndex == 2) { request.status = 10; } if (cbStatus.SelectedIndex == 3) { request.status = 15; } if (cbStatus.SelectedIndex == 4) { request.status = 20; } PackTaskResponse response = client.Execute(request); if (!response.IsError) { if (response.result == null) { this.dataGridView1.DataSource = null; return; } int recordCount = response.pageUtil.totalRow; int totalPage; if (recordCount % paginator.PageSize == 0) { totalPage = recordCount / paginator.PageSize; } else { totalPage = recordCount / paginator.PageSize + 1; } foreach (PackTask item in response.result) { if (item.modelNum > 0) { decimal curValue = item.orderCount / item.modelNum; item.StandNum = (int)curValue; } if (item.orderNum > 0) { item.progressDes = ((item.finishNum / item.orderNum) * 100).ToString() + "%"; } } IPagedList<PackTask> pageList = new PagedList<PackTask>(response.result, recordCount, totalPage); sortList = new SortableBindingList<PackTask>(pageList.ContentList); this.dataGridView1.DataSource = sortList; pageSplit1.Description = "共查询到" + pageList.RecordCount + "条记录"; pageSplit1.PageCount = pageList.PageCount; pageSplit1.PageNo = paginator.PageNo; pageSplit1.DataBind(); } } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex >= 0) { DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex]; if (column is DataGridViewButtonColumn) { int status = int.Parse(this.dataGridView1.CurrentRow.Cells["status"].Value.ToString()); if (status==15||status==20) { MessageBox.Show("当前任务已完成"); return; } long id = long.Parse(this.dataGridView1.CurrentRow.Cells["id"].Value.ToString()); string taskCode = this.dataGridView1.CurrentRow.Cells["PackTaskCode"].Value.ToString(); decimal orderCount = decimal.Parse(this.dataGridView1.CurrentRow.Cells["orderCount"].Value.ToString()); int standNum=int.Parse(this.dataGridView1.CurrentRow.Cells["StandNum"].Value.ToString()); int orderNum=int.Parse(this.dataGridView1.CurrentRow.Cells["orderNum"].Value.ToString()); string processDes = this.dataGridView1.CurrentRow.Cells["progressDes"].Value.ToString(); string warehouseName =this.dataGridView1.CurrentRow.Cells["warehouseName"].Value==null?"": this.dataGridView1.CurrentRow.Cells["warehouseName"].Value.ToString(); //这里可以编写你需要的任意关于按钮事件的操作~ WeightForm weightForm = new WeightForm(id, taskCode, orderCount, standNum, processDes, orderNum); weightForm.wareHouseName = warehouseName; if (weightForm.ShowDialog() == DialogResult.OK) { BindDgv(); } } } } private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { var grid = sender as DataGridView; var rowIdx = (e.RowIndex + 1).ToString(); var centerFormat = new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }; var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height); e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat); } private void btnQuery_Click(object sender, EventArgs e) { paginator.PageNo = 1; BindDgv(); } private void pageSplit1_PageChanged(object sender, EventArgs e) { paginator.PageNo = pageSplit1.PageNo; BindDgv(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum PlayerState { idle, walk, attack, interact, stagger } public class PlayerMovement : MonoBehaviour { [SerializeField] private float _speed; private PlayerState _currentState; private Rigidbody2D _myRigidBody; private Animator _myAnimator; private Vector3 _change; public FloatValue _currentHealth; public SignalScript _playerHealthSignal; public VectorValue _startingPosition; public PlayerState GetCurrentState() { return _currentState; } private void Start() { _myRigidBody = GetComponent<Rigidbody2D>(); _myAnimator = GetComponent<Animator>(); ChangeState(PlayerState.idle); _myAnimator.SetFloat("moveX", 0); _myAnimator.SetFloat("moveY", -1); transform.position = _startingPosition._initialValue; } private void Update() { _change = Vector3.zero; _change.x = Input.GetAxisRaw("Horizontal"); _change.y = Input.GetAxisRaw("Vertical"); //neu trang thai hien tai la walk/idle //neu co thay doi change --> chuyen thanh walk //va nguoc lai if(_currentState == PlayerState.idle || _currentState == PlayerState.walk) { if(_change != Vector3.zero) { ChangeState(PlayerState.walk); } else { ChangeState(PlayerState.idle); } } //neu trang thai la walk/idle thi kiem tra xem co an nut attack khong //neu co thi thuc hien tan cong //roi neu khong tan cong thi moi chuyen qua update animation di chuyen if (_currentState == PlayerState.walk || _currentState == PlayerState.idle) { if (Input.GetButtonDown("attack")) { StartCoroutine(Attack()); } else { UpdateAnimation(); } } } private void FixedUpdate() {//neu trang thai hien tai la di chuyen ma co su thay doi //do trang thai hien tai da la walk/idle roi nen khong can them dieu kien nua MoveCharacter(); } //ham de di chuyen nhan vat private void MoveCharacter() { if (_currentState == PlayerState.walk) { _myRigidBody.MovePosition(transform.position + _change.normalized * _speed * Time.fixedDeltaTime); } } private void UpdateAnimation() { if(_currentState == PlayerState.walk) { _myAnimator.SetFloat("moveX", _change.x); _myAnimator.SetFloat("moveY", _change.y); _myAnimator.SetBool("moving", true); } else if(_currentState == PlayerState.idle) { _myAnimator.SetBool("moving", false); } } private IEnumerator Attack() { ChangeState(PlayerState.attack); _myAnimator.SetBool("attacking", true); yield return null; _myAnimator.SetBool("attacking", false); yield return new WaitForSeconds(.3f); ChangeState(PlayerState.idle); } //ham dung de thay doi state nhan vat public void ChangeState(PlayerState state) { if (_currentState != state) { _currentState = state; } } public void Knock(float knockTime, float damage) { _currentHealth._runtimeValue -= damage; _playerHealthSignal.Raise(); if (_currentHealth._runtimeValue > 0) { StartCoroutine(KnockCo(knockTime)); }else { this.gameObject.SetActive(false); } } private IEnumerator KnockCo(float knockTime) { if (_myRigidBody != null) { yield return new WaitForSeconds(knockTime); _myRigidBody.velocity = Vector2.zero; this.ChangeState(PlayerState.idle); _myRigidBody.velocity = Vector2.zero; } } }
using System; using MediaOrganiser.Media.Movies.Details; namespace MediaOrganiser.Media.Movies { public interface IMovie : IMedia, IMovieDetailsBasic { } }
using Assets.Scripts.RobinsonCrusoe_Game.GameAttributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assets.Scripts.RobinsonCrusoe_Game.Cards.EventCards.Collection { public class EventCard_DevastatingHurricane : IEventCard, ICard { public bool CanCompleteQuest() { return true; } private int eventNumber = 0; public void ExecuteEvent() { if (eventNumber == 0) { ExecuteActiveThreat(); eventNumber++; } else { ExecuteFutureThreat(); } } private void ExecuteFutureThreat() { Wall.DowngradeWallBy(1); //TODO: implement choice between wall and weapons } private void ExecuteActiveThreat() { int state = Wall.WallState; double half = state / 2; state = Convert.ToInt32(half); Wall.DowngradeWallBy(state); //TODO: implement choice between wall and weapons } public void ExecuteSuccessEvent() { Wall.UpgradeWallBy(1); //TODO: implement choice between wall and weapons } public int GetActionCosts() { return 1; } public string GetCardDescription() { if (eventNumber == 0) { return "Dein/Euer Wall wird halbiert(abgerundet)."; } else { return "Du/Ihr verliert 1 Wall."; } } public int GetMaterialNumber() { return 51; } public QuestionMark GetQuestionMark() { return QuestionMark.Gathering; } public RessourceCosts GetRessourceCosts() { return new RessourceCosts(1, 0, 0); } public bool IsCardTypeBook() { return false; } public override string ToString() { return "Devastating Hurricane"; } public bool HasDiscardOption() { return false; } } }
using System; using Server; using Server.Items; using Server.Mobiles; using Server.Network; using Server.Engines.Craft; namespace Server.Items { public enum RuneQuality { Low, Regular, Exceptional } public class BaseMinorRune : Item, ICraftable { private Mobile m_Crafter; private int m_MaxAmount; private int m_BaseAmount; private RuneQuality m_Quality; [CommandProperty( AccessLevel.GameMaster )] public Mobile Crafter { get{ return m_Crafter; } set{ m_Crafter = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public int MaxAmount { get{ return m_MaxAmount; } set{ m_MaxAmount = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public int BaseAmount { get{ return m_BaseAmount; } set{ m_BaseAmount = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public RuneQuality Quality { get{ return m_Quality; } set{ m_Quality = value; InvalidateProperties(); } } public BaseMinorRune() : base( 0x1F17 ) { Name = "a minor enchanted rune"; Hue = 1150; } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( m_Quality == RuneQuality.Exceptional ) list.Add( 1063341 ); // exceptional if ( m_Crafter != null ) list.Add( 1050043, m_Crafter.Name ); // crafted by ~1_NAME~ } public BaseMinorRune( Serial serial ) : base( serial ) { } public virtual int OnCraft( int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, BaseTool tool, CraftItem craftItem, int resHue ) { Double bonus = (Double)quality * 5; Double imbuing = from.Skills.Imbuing.Value / 4 + bonus; Double amount = imbuing / 100.0 * (Double)this.MaxAmount; this.BaseAmount = (int)amount; if ( this.BaseAmount == 0 ) this.BaseAmount = 1; if ( makersMark ) Crafter = from; m_Quality = (RuneQuality)quality; return quality; } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version // Release writer.Write( (Mobile) m_Crafter ); writer.Write( (int) m_MaxAmount ); writer.Write( (int) m_BaseAmount ); writer.WriteEncodedInt( (int) m_Quality ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch( version ) { case 0: { m_Crafter = reader.ReadMobile(); m_MaxAmount = reader.ReadInt(); m_BaseAmount = reader.ReadInt(); m_Quality = (RuneQuality)reader.ReadEncodedInt(); break; } } } } }
using Accounting.DataAccess; using Accounting.Utility; using AccSys.Web.Models; using AccSys.Web.WebControls; using System; using System.Data; using System.Data.SqlClient; using System.Web.UI.WebControls; using Tools; namespace AccSys.Web { public partial class frmSaleOrder : BasePage { private string _sessionDatatableName = "SalesOrderItems"; private string _dateFormat = "yyyy-MM-dd"; private DataTable GetSessionDataTable() { DataTable dtItems; if (Session[_sessionDatatableName] == null) { dtItems = new DataTable(); dtItems.Columns.Add("ID", typeof(int)); dtItems.Columns.Add("ItemID", typeof(int)); dtItems.Columns.Add("ItemName", typeof(string)); dtItems.Columns.Add("Qty", typeof(double)); dtItems.Columns.Add("UnitPrice", typeof(double)); dtItems.Columns.Add("Amount", typeof(double)); } else { dtItems = (DataTable)Session[_sessionDatatableName]; } return dtItems; } protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { txtDate.Text = DateTime.Now.ToString(_dateFormat); txtFromDate.Text = string.Format("{0:" + _dateFormat + "}", DateTime.Now.AddDays(-30)); txtToDate.Text = string.Format("{0:" + _dateFormat + "}", DateTime.Now); Session[_sessionDatatableName] = null; btnSearch_Click(sender, e); } } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } private void CalculateTotal(DataTable dtItems) { txtQty.Text = ""; txtUnitPrice.Text = ""; double totalQty = 0.0, totalAmt = 0.0; foreach (DataRow r in dtItems.Rows) { totalQty += Tools.Utility.IsNull<double>(r["Qty"], 0.0); totalAmt += Tools.Utility.IsNull<double>(r["Amount"], 0.0); } txtTotalQty.Text = string.Format("{0}", totalQty); txtTotalAmount.Text = string.Format("{0}", totalAmt); } private void ChangeValue(object sender, string fieldName) { TextBox txtSender = (TextBox)sender; Label lblRowItemId = (Label)txtSender.NamingContainer.FindControl("lblItemId"); int itemId = lblRowItemId.Text.ToInt(); Label lblRowAmount = (Label)txtSender.NamingContainer.FindControl("lblAmount"); DataTable dtItems = GetSessionDataTable(); foreach (DataRow row in dtItems.Rows) { if (GlobalFunctions.isNull(row["ItemID"], 0) == itemId) { row[fieldName] = txtSender.Text.ToDouble(); row["Amount"] = GlobalFunctions.isNull(row["Qty"], 0.0) * GlobalFunctions.isNull(row["UnitPrice"], 0.0); lblRowAmount.Text = string.Format("{0:0.00}", row["Amount"]); break; } } CalculateTotal(dtItems); Session[_sessionDatatableName] = dtItems; } protected void txtQty_TextChanged(object sender, EventArgs e) { ChangeValue(sender, "Qty"); } protected void txtUnitPrice_TextChanged(object sender, EventArgs e) { ChangeValue(sender, "UnitPrice"); } protected void btnAdd_Click(object sender, EventArgs e) { try { DataTable dtItems = GetSessionDataTable(); int ItemID = Convert.ToInt32(ddlItem.SelectedValue); if (ItemID <= 0) return; foreach (DataRow r in dtItems.Rows) { if (Tools.Utility.IsNull<int>(r["ItemID"], 0) == ItemID) { return; } } var qty = Convert.ToDouble(txtQty.Text.Trim()); var price = Convert.ToDouble(txtUnitPrice.Text.Trim()); var rate = txtRate.Text.Trim().ToDouble(); var amt = qty * price * rate; dtItems.Rows.Add(0, ItemID, ddlItem.SelectedItemName(), qty, price, amt); gvOrderItems.DataSource = dtItems; gvOrderItems.DataBind(); CalculateTotal(dtItems); Session[_sessionDatatableName] = dtItems; lblMsg.Text = ""; } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } protected void btnRemove_Click(object sender, EventArgs e) { try { Label lblItemId = (Label)((LinkButton)sender).NamingContainer.FindControl("lblItemId"); int ItemId = Convert.ToInt32(lblItemId.Text); DataTable dtInvItems = (DataTable)Session[_sessionDatatableName]; foreach (DataRow r in dtInvItems.Rows) { if (Tools.Utility.IsNull<int>(r["ItemID"], 0) == ItemId) { dtInvItems.Rows.Remove(r); break; } } gvOrderItems.DataSource = dtInvItems; gvOrderItems.DataBind(); CalculateTotal(dtInvItems); Session[_sessionDatatableName] = dtInvItems; lblMsg.Text = ""; } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } protected void btnReset_Click(object sender, EventArgs e) { try { ddlCustomer.SelectedIndex = 1; txtDate.Text = DateTime.Now.ToString(_dateFormat); txtDeliveryDate.Text = ""; ddlCurrency.SelectedIndex = 0; txtRate.Text = "1"; txtOrderNo.Text = ""; txtLedgerNo.Text = ""; txtBuyerref.Text = ""; Session[_sessionDatatableName] = null; var dtItems = GetSessionDataTable(); gvOrderItems.DataSource = dtItems; gvOrderItems.DataBind(); txtTotalQty.Text = "0"; txtTotalAmount.Text = "0"; if (sender.Equals(btnReset)) lblMsg.Text = ""; } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } private SaleOrderModel CreateModel() { var model = new SaleOrderModel { OrderId = lblOrderId.Text.ToInt(), OrderDate = Tools.Utility.GetDateValue(txtDate.Text.Trim(), DateNumericFormat.YYYYMMDD), DeliveryDate = txtDeliveryDate.Text.Trim() == "" ? new DateTime(1900,1,1): Tools.Utility.GetDateValue(txtDeliveryDate.Text.Trim(), DateNumericFormat.YYYYMMDD), OrderNo = txtOrderNo.Text, LedgerNo = txtLedgerNo.Text, CurrencyId = ddlCurrency.SelectedValue.ToInt(), CurrencyRate = txtRate.Text.ToDouble(), OrderQty = txtTotalQty.Text.ToDouble(), OrderValue = txtTotalAmount.Text.ToDouble(), BuyerRef = txtBuyerref.Text, CustomerId = ddlCustomer.SelectedValue.ToInt(), CompanyId = Session.CompanyId() }; if (Session[_sessionDatatableName] != null) { model.OrderItems = (DataTable)Session[_sessionDatatableName]; } else { model.OrderItems = new DataTable(); } return model; } protected void btnSave_Click(object sender, EventArgs e) { var daOrder = new DaOrder(); SqlTransaction trans = null; SqlConnection connection = null; try { var model = CreateModel(); var errors = model.ValidationErrors; if (errors.Count > 0) { lblMsg.Text = UIMessage.Message2User(string.Join("<br/>", errors), UserUILookType.Warning); return; } connection = ConnectionHelper.getConnection(); trans = connection.BeginTransaction(); if (model.OrderId > 0) { daOrder.DeleteOrderItems(connection, trans, model.OrderId); } model.OrderId = daOrder.saveUpdateOrderMaster(model.OrderMaster, trans, connection); foreach (var item in model.OrderDetails) { daOrder.saveUpdateOrder_Details(item, trans, connection); } trans.Commit(); connection.Close(); lblMsg.Text = UIMessage.Message2User("Successfully saved", UserUILookType.Success); btnReset_Click(sender, e); btnSearch_Click(sender, e); } catch (Exception ex) { if (trans != null) trans.Rollback(); if (connection != null) connection.Close(); lblMsg.Text = ex.CustomDialogMessage(); } } private string CreateWhere() { string where = string.Format(" Order_Master.CompanyID={0} AND OrderType = 'Sales Order'", Session.CompanyId()); where += string.Format(" AND (OrderDate BETWEEN '{0:yyyy-MM-dd}' AND '{1:yyyy-MM-dd}')", Tools.Utility.GetDateValue(txtFromDate.Text.Trim(), DateNumericFormat.YYYYMMDD), Tools.Utility.GetDateValue(txtToDate.Text.Trim(), DateNumericFormat.YYYYMMDD)); return where; } protected void btnSearch_Click(object sender, EventArgs e) { try { gvData.DataSourceID = "odsCommon"; odsCommon.SelectParameters["SelectedColumns"].DefaultValue = @" OrderMID AS OrderID, OrderNo, OrderDate, CustomerID, LedgerName AS CustomerName, TotalOrderQty AS OrderQty, OrderValue, Buyer_ref, Order_Master.CompanyID "; odsCommon.SelectParameters["FromTable"].DefaultValue = @" Order_Master LEFT OUTER JOIN T_Ledgers ON Order_Master.CustomerID = T_Ledgers.LedgerID "; odsCommon.SelectParameters["Where"].DefaultValue = CreateWhere(); odsCommon.SelectParameters["OrderBy"].DefaultValue = " OrderDate DESC "; if (sender != null) gvData.PageIndex = 0; gvData.DataBind(); if (sender.Equals(btnSearch)) lblMsg.Text = ""; } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } protected void lbtnDelete_Click(object sender, EventArgs e) { Label lblRowId = (Label)((LinkButton)sender).NamingContainer.FindControl("lblId"); int orderId = lblRowId.Text.ToInt(); SqlConnection connection = null; SqlTransaction trans = null; try { connection = ConnectionHelper.getConnection(); trans = connection.BeginTransaction(); new DaOrder().Delete(connection, trans, orderId); trans.Commit(); connection.Close(); lblMsg.Text = UIMessage.Message2User("Successfully deleted", UserUILookType.Success); btnSearch_Click(sender, e); } catch (Exception ex) { if (trans != null) trans.Rollback(); if (connection != null) connection.Close(); lblMsg.Text = ex.CustomDialogMessage(); } finally { if (connection.State != ConnectionState.Closed) connection.Close(); } } protected void lbtnEdit_Click(object sender, EventArgs e) { try { Label lblRowId = (Label)((LinkButton)sender).NamingContainer.FindControl("lblId"); int orderId = lblRowId.Text.ToInt(); var connection = ConnectionHelper.getConnection(); var order = new DaOrder().GetOrder_Master(connection, orderId); if (order == null) return; lblOrderId.Text = lblRowId.Text; txtOrderNo.Text = order.OrderNo; txtLedgerNo.Text = order.LedgerNo; txtDate.Text = order.OrderDate.ToString(_dateFormat); txtDeliveryDate.Text = order.DeliveryDate == new DateTime(1900,1,1) ? "" : order.DeliveryDate.ToString(_dateFormat); ddlCurrency.SelectedValue = order.CurrencyID.ToString(); txtRate.Text = "1"; ddlCustomer.SelectedValue = order.CustomerID.ToString(); txtBuyerref.Text = order.Buyer_ref; Session[_sessionDatatableName] = null; var dtItems = GetSessionDataTable(); var orderItems = new DaOrder().GetOrderItems(connection, orderId); foreach (DataRow row in orderItems.Rows) { dtItems.Rows.Add(0, row["ItemID"], row["ItemName"], row["OrderQty"], row["UnitPrice"], row["OrderValue"]); } gvOrderItems.DataSource = dtItems; gvOrderItems.DataBind(); CalculateTotal(dtItems); Session[_sessionDatatableName] = dtItems; lblMsg.Text = ""; } catch (Exception ex) { lblMsg.Text = ex.CustomDialogMessage(); } } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("DeckRule_CountCardsInDeck")] public class DeckRule_CountCardsInDeck : DeckRule { public DeckRule_CountCardsInDeck(IntPtr address) : this(address, "DeckRule_CountCardsInDeck") { } public DeckRule_CountCardsInDeck(IntPtr address, string className) : base(address, className) { } } }
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.OleDb; public partial class Yonetici_Siparis : System.Web.UI.Page { DataTable _dtUrun; DataTable _dtUrunDuzenle; public DataTable _dtSiparis; Data _sysData = new Data(); private bool _blDuzenle; OleDbConnection _cnn; OleDbCommand _cmd; string Baglan = "Provider=Microsoft.jet.OLEDB.4.0; data source=" + HttpContext.Current.Server.MapPath("~/App_Data\\MercanYazilimDataBase.mdb"); protected void Page_Load(object sender, EventArgs e) { if (Session["idYonetici"] == null) { Response.Redirect("Giris.aspx"); } if (!Page.IsPostBack) { _fncSiparisGetir(); } } private void _fncSiparisGetir() { _dtSiparis = new DataTable(); _dtSiparis = _sysData._fncSelect("SELECT [Siparis.idSiparis],[Paket.PaketAdi],[Siparis.Domain],[Siparis.Ad],[Siparis.Soyad],[Siparis.Telefon],[Siparis.Email],[Siparis.Tarih] FROM Siparis INNER JOIN Paket ON Siparis.idPaket = Paket.idPaket"); } }
using System; using System.Collections.Generic; using System.Text; namespace OCP { /** * Class Constants * * @package OCP * @since 8.0.0 */ public static class Constants { /** * CRUDS permissions. * @since 8.0.0 */ public static int PERMISSION_CREATE => 4; public static int PERMISSION_READ => 1; public static int PERMISSION_UPDATE => 2; public static int PERMISSION_DELETE => 8; public static int PERMISSION_SHARE => 16; public static int PERMISSION_ALL => 31; /** * @since 8.0.0 - Updated in 9.0.0 to allow all POSIX chars since we no * longer support windows as server platform. */ public static string FILENAME_INVALID_CHARS => "\\/"; public const string PREVIEW_MODE_FILE = "fill"; public const string PREVIEW_MODE_COVER = "cover"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sunny.MiniMvc.Web { public class SimpleModel { public string Test1 { get; set; } public string Test2 { get; set; } public string Test3 { get; set; } } }
// <copyright file="ReadBookDto.cs" company="PlaceholderCompany"> // Copyright (c) PlaceholderCompany. All rights reserved. // </copyright> namespace AspNetSandbox.DTOs { public class ReadBookDto { public int Id { get; set; } public string Title { get; set; } public string Author { get; set; } public string Language { get; set; } } }
namespace ProConstructionsManagment.Desktop.Messages { public class ProjectRecruitmentIdMessage { public ProjectRecruitmentIdMessage(string projectRecruitmentId) { ProjectRecruitmentId = projectRecruitmentId; } public string ProjectRecruitmentId { get; } } }
namespace CommandPattern { public class CloseFileCommand : ICommand { private IFile _file; public CloseFileCommand(IFile file) { this._file = file; } public void Execute() { this._file.Close(); } } }
using System; using System.Collections.Generic; namespace SheMediaConverterClean.Infra.Data.Models { public partial class VAlleVerweise { public int? Inhaber { get; set; } public Guid VerweisGuid { get; set; } public int? FuerBenutzer { get; set; } public Guid FuerBenutzerGuid { get; set; } } }
namespace MH_Database.Ressources.Items_Data { partial class Weapons { internal MonsterHunter3U MH3U = new MonsterHunter3U(); } }
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 System.IO.Ports; using System.Threading; using System.IO; namespace WindowsFormsApplication1 { public partial class Form1 : Form { SerialPort serialPort = null; delegate void AddDataDelegate(String myString); AddDataDelegate myDelegate; String filePath = @"D:\Arduion file\arduino.txt"; delegate void addLevel1(double number); addLevel1 level1; public Form1() { InitializeComponent(); setInitForm(); this.myDelegate = new AddDataDelegate(AddDataMethod); this.level1 = new addLevel1(AddLevel1); } private void AddLevel1(double number) { LabelSat.Text = Convert.ToString(number); } private void setInitForm() { //button setting stopButton.Enabled = false; saveButton.Enabled = true; serialPort = new SerialPort(); foreach (String com in SerialPort.GetPortNames()) { serialPortComBox.Items.Add(com); } } private void startButton_Click(object sender, EventArgs e) { if (serialPortComBox.Text == null || "".Equals(serialPortComBox.Text)) { MessageBox.Show("Please select the serial port first", "Error"); return; } startButton.Enabled = false; stopButton.Enabled = true; saveButton.Enabled = false; openSerailPort(); } private void openSerailPort() { try { serialPort.PortName = serialPortComBox.Text; serialPort.BaudRate = 38400; //serialPort.DataBits = 8; serialPort.DataReceived += new SerialDataReceivedEventHandler(serialDataReceivedEventHandler); // serialPort.ReadTimeout = 5000; serialPort.Open(); } catch (Exception e) { MessageBox.Show("Serial Port open fail : " + e.ToString()); } } unsafe void serialDataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e) { Byte[] buffer = new Byte[1024]; Int16 s16RfAck, s16CapMsb, s16CapLsb, s16Ax = 0, s16Ay = 0, s16Az = 0, s16Gx = 0, s16Gy = 0, s16Gz = 0; int s32Cap; double fCap, fSat, fIncX, fIncY; SerialPort port = (SerialPort)sender; if (port.IsOpen && port.BytesToRead > 0) { Int32 length = port.Read(buffer, 0, buffer.Length); Array.Resize(ref buffer, length); /* s16RfAck = (Int16)(buffer[0] << 8 | buffer[1]); s16CapMsb = (Int16)(buffer[2] << 8 | buffer[3]); s16CapLsb = (Int16)(buffer[4] << 8 | buffer[5]); s16Ax = (Int16)(buffer[6] << 8 | buffer[7]); s16Ay = (Int16)(buffer[8] << 8 | buffer[9]); s16Az = (Int16)(buffer[10] << 8 | buffer[11]); s16Gx = (Int16)(buffer[12] << 8 | buffer[13]); s16Gy = (Int16)(buffer[14] << 8 | buffer[15]); s16Gz = (Int16)(buffer[16] << 8 | buffer[17]); s32Cap = s16CapMsb << 16 | s16CapLsb; fCap = (double)s32Cap; fCap /= 134217728; fSat = 1.32 * fCap * fCap + 0.44 * fCap - 19.17; //LabelSat.Text = Convert.ToString(fSat); //LabelCap.Text = Convert.ToString(fCap); //LabelIncX.Text = Convert.ToString(fIncX); //LabelIncY.Text = Convert.ToString(fIncY); */ String secondResult = System.Text.Encoding.UTF8.GetString(buffer); resultText.Invoke(this.myDelegate, secondResult); //LabelSat.Invoke(this.level1, fSat); } Thread.Sleep(1000); } private void stopButton_Click(object sender, EventArgs e) { serialPort.Close(); startButton.Enabled = true; saveButton.Enabled = true; } public void AddDataMethod(String myString) { resultText.AppendText(myString + Environment.NewLine); } private void saveButton_Click(object sender, EventArgs e) { if (resultText.TextLength > 0) { if (!File.Exists(filePath)) { using (StreamWriter sw = File.CreateText(filePath)) { sw.WriteLine(resultText.Text); sw.Close(); } } else if (File.Exists(filePath)) { using (StreamWriter sw = File.AppendText(filePath)) { sw.WriteLine(resultText.Text); } } MessageBox.Show("Save successfully", "Note"); } else { MessageBox.Show("No data to save", "Error"); return; } } private void resultText_TextChanged(object sender, EventArgs e) { } private void serialPortComBox_SelectedIndexChanged(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void LabelCap_Click(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Accounting.Entity { public class BusinessType : BaseObject { public BusinessType() :base() { } #region Fields private int numBusinessTypeID; private string strName; #endregion #region Properties public int BusinessTypeID { get { return numBusinessTypeID; } set { numBusinessTypeID = value; } } public string Name { get { return strName; } set { strName = value; } } #endregion } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Windows.Forms; namespace MailCommander { class Helper { public static MainForm MainForm; public static string GetRootPath() { return Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); } public static void LoanConnectionComboBox(ComboBox comboBox) { comboBox.Items.Clear(); foreach (ConnectionStringSettings conn in ConfigurationManager.ConnectionStrings) { comboBox.Items.Add(conn.Name); } } public static string GetMailCommandListFileName() { return Helper.GetRootPath() + "\\MailCommandList.xml"; } public static MailCommandDataSet GetMailCommandDataSet() { MailCommandDataSet result = new MailCommandDataSet(); string filePath = Helper.GetMailCommandListFileName(); result.ReadXml(filePath); return result; } public static MailCommand GetMailCommand(MailCommandDataSet mailCommandDataSet, string command) { MailCommand result = new MailCommand(); DataRow[] dr = mailCommandDataSet.Tables[0].Select("Command='" + command + "'"); if (dr.Length == 0) throw new Exception("No command found for " + command); if (dr.Length > 1) throw new Exception("Too many command found for " + command); result.Command = dr[0]["Command"].ToString(); result.Connection = dr[0]["Connection"].ToString(); result.Description = dr[0]["Description"].ToString(); result.SqlCommandText = dr[0]["SqlCommandText"].ToString(); result.CommandType = CommandType.MailCommand; return result; } public static MailCommand GetMailCommand(string command) { return GetMailCommand(GetMailCommandDataSet(), command); } public static DataSet GetCommandList() { DataSet result = GetMailCommandDataSet().Copy(); foreach(DataRow dr in result.Tables[0].Rows) { dr["SqlCommandText"] = ""; } return result; } public static void ColorizeRichTextBox(RichTextBox richTextBox) { foreach (string key in GetTsqlReservedKeywords()) { ColorizeText(richTextBox, 0, key, Color.Blue); } } private static void ColorizeText(RichTextBox richTextBox, int startIndex, string text, Color color) { int resultIndex = richTextBox.Find(text, startIndex, RichTextBoxFinds.WholeWord); if (resultIndex != -1) { richTextBox.SelectionColor = color; ColorizeText(richTextBox, resultIndex + 1, text, color); } } private static List<string> GetTsqlReservedKeywords() { List<string> result = new List<string>(); result.Add("ADD"); result.Add("EXTERNAL"); result.Add("PROCEDURE"); result.Add("ALL"); result.Add("FETCH"); result.Add("PUBLIC"); result.Add("ALTER"); result.Add("FILE"); result.Add("RAISERROR"); result.Add("AND"); result.Add("FILLFACTOR"); result.Add("READ"); result.Add("ANY"); result.Add("FOR"); result.Add("READTEXT"); result.Add("AS"); result.Add("FOREIGN"); result.Add("RECONFIGURE"); result.Add("ASC"); result.Add("FREETEXT"); result.Add("REFERENCES"); result.Add("AUTHORIZATION"); result.Add("FREETEXTTABLE"); result.Add("REPLICATION"); result.Add("BACKUP"); result.Add("FROM"); result.Add("RESTORE"); result.Add("BEGIN"); result.Add("FULL"); result.Add("RESTRICT"); result.Add("BETWEEN"); result.Add("FUNCTION"); result.Add("RETURN"); result.Add("BREAK"); result.Add("GOTO"); result.Add("REVERT"); result.Add("BROWSE"); result.Add("GRANT"); result.Add("REVOKE"); result.Add("BULK"); result.Add("GROUP"); result.Add("RIGHT"); result.Add("BY"); result.Add("HAVING"); result.Add("ROLLBACK"); result.Add("CASCADE"); result.Add("HOLDLOCK"); result.Add("ROWCOUNT"); result.Add("CASE"); result.Add("IDENTITY"); result.Add("ROWGUIDCOL"); result.Add("CHECK"); result.Add("IDENTITY_INSERT"); result.Add("RULE"); result.Add("CHECKPOINT"); result.Add("IDENTITYCOL"); result.Add("SAVE"); result.Add("CLOSE"); result.Add("IF"); result.Add("SCHEMA"); result.Add("CLUSTERED"); result.Add("IN"); result.Add("SECURITYAUDIT"); result.Add("COALESCE"); result.Add("INDEX"); result.Add("SELECT"); result.Add("COLLATE"); result.Add("INNER"); result.Add("SEMANTICKEYPHRASETABLE"); result.Add("COLUMN"); result.Add("INSERT"); result.Add("SEMANTICSIMILARITYDETAILSTABLE"); result.Add("COMMIT"); result.Add("INTERSECT"); result.Add("SEMANTICSIMILARITYTABLE"); result.Add("COMPUTE"); result.Add("INTO"); result.Add("SESSION_USER"); result.Add("CONSTRAINT"); result.Add("IS"); result.Add("SET"); result.Add("CONTAINS"); result.Add("JOIN"); result.Add("SETUSER"); result.Add("CONTAINSTABLE"); result.Add("KEY"); result.Add("SHUTDOWN"); result.Add("CONTINUE"); result.Add("KILL"); result.Add("SOME"); result.Add("CONVERT"); result.Add("LEFT"); result.Add("STATISTICS"); result.Add("CREATE"); result.Add("LIKE"); result.Add("SYSTEM_USER"); result.Add("CROSS"); result.Add("LINENO"); result.Add("TABLE"); result.Add("CURRENT"); result.Add("LOAD"); result.Add("TABLESAMPLE"); result.Add("CURRENT_DATE"); result.Add("MERGE"); result.Add("TEXTSIZE"); result.Add("CURRENT_TIME"); result.Add("NATIONAL"); result.Add("THEN"); result.Add("CURRENT_TIMESTAMP"); result.Add("NOCHECK"); result.Add("TO"); result.Add("CURRENT_USER"); result.Add("NONCLUSTERED"); result.Add("TOP"); result.Add("CURSOR"); result.Add("NOT"); result.Add("TRAN"); result.Add("DATABASE"); result.Add("NULL"); result.Add("TRANSACTION"); result.Add("DBCC"); result.Add("NULLIF"); result.Add("TRIGGER"); result.Add("DEALLOCATE"); result.Add("OF"); result.Add("TRUNCATE"); result.Add("DECLARE"); result.Add("OFF"); result.Add("TRY_CONVERT"); result.Add("DEFAULT"); result.Add("OFFSETS"); result.Add("TSEQUAL"); result.Add("DELETE"); result.Add("ON"); result.Add("UNION"); result.Add("DENY"); result.Add("OPEN"); result.Add("UNIQUE"); result.Add("DESC"); result.Add("OPENDATASOURCE"); result.Add("UNPIVOT"); result.Add("DISK"); result.Add("OPENQUERY"); result.Add("UPDATE"); result.Add("DISTINCT"); result.Add("OPENROWSET"); result.Add("UPDATETEXT"); result.Add("DISTRIBUTED"); result.Add("OPENXML"); result.Add("USE"); result.Add("DOUBLE"); result.Add("OPTION"); result.Add("USER"); result.Add("DROP"); result.Add("OR"); result.Add("VALUES"); result.Add("DUMP"); result.Add("ORDER"); result.Add("VARYING"); result.Add("ELSE"); result.Add("OUTER"); result.Add("VIEW"); result.Add("END"); result.Add("OVER"); result.Add("WAITFOR"); result.Add("ERRLVL"); result.Add("PERCENT"); result.Add("WHEN"); result.Add("ESCAPE"); result.Add("PIVOT"); result.Add("WHERE"); result.Add("EXCEPT"); result.Add("PLAN"); result.Add("WHILE"); result.Add("EXEC"); result.Add("PRECISION"); result.Add("WITH"); result.Add("EXECUTE"); result.Add("PRIMARY"); result.Add("WITHIN GROUP"); result.Add("EXISTS"); result.Add("PRINT"); result.Add("WRITETEXT"); result.Add("EXIT"); result.Add("PROC"); result.Add("GO"); return result; } } }
using Microsoft.AspNetCore.Authorization; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AuthAutho.Extensions { /// <summary> /// Classe responsavel por criar forma de autenticaçao com clains em que /// voce tem uma claim do tipo Permissao e tem os valores para essa permissao /// PodeLer, PodeEscrever, PodeExcluir. /// esse tipo de implementação é a recomendação da microsoft /// tem que fazer a implemetação aqui e tb na startup /// </summary> public class PermissaoNecessaria : IAuthorizationRequirement { public string Permissao { get; set; } public PermissaoNecessaria(string permissao) { Permissao = permissao; } } /// <summary> /// AuthorizationHelper implementa a IAuthorizationHandler para injeção de dependencia /// </summary> public class PermissaoNecessariaHandler : AuthorizationHandler<PermissaoNecessaria> { protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissaoNecessaria requisito) { if(context.User.HasClaim(c=> c.Type == "Permissao" && c.Value.Contains(requisito.Permissao))) { context.Succeed(requisito); } return Task.CompletedTask; } } }
namespace BitcoinAddressGenerator { using System; using System.Globalization; using System.Numerics; using System.Security.Cryptography; public class Startup { public static void Main() { var hexHash = "0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"; var publicKey = HexToByte(hexHash); Console.WriteLine("Public Key: " + ByteToHex(publicKey)); var publicKeySHA256 = SHA256(publicKey); Console.WriteLine("SHA Public Key: " + ByteToHex(publicKeySHA256)); var publicKeySHARIPE = RIPEMD160(publicKeySHA256); Console.WriteLine("RIPE SHA Public Key: " + ByteToHex(publicKeySHARIPE)); var preHashNetwork = AppendBitcoinNetwork(publicKeySHARIPE, 0); var publicHash = SHA256(preHashNetwork); Console.WriteLine("Public Hash: " + ByteToHex(publicHash)); var publicHashHash = SHA256(publicHash); Console.WriteLine("Public HashHash: " + ByteToHex(publicHashHash)); Console.WriteLine("Checksum: " + ByteToHex(publicHashHash).Substring(0, 4)); var address = ConcatAddress(preHashNetwork, publicHashHash); Console.WriteLine("Address: " + ByteToHex(address)); Console.WriteLine("Human Address: " + Base58Encode(address)); } private static byte[] HexToByte(string hexString) { if (hexString.Length % 2 != 0) { throw new InvalidOperationException("Invalid HEX"); } var array = new byte[hexString.Length / 2]; for (int i = 0; i < array.Length; ++i) { array[i] = byte.Parse(hexString.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); } return array; } private static string ByteToHex(byte[] publicKeySHA) { var hex = BitConverter.ToString(publicKeySHA); return hex; } private static byte[] SHA256(byte[] array) { var hash = new SHA256Managed(); return hash.ComputeHash(array); } private static byte[] RIPEMD160(byte[] array) { var hash = new RIPEMD160Managed(); return hash.ComputeHash(array); } private static byte[] AppendBitcoinNetwork(byte[] ripeHash, byte network) { var extended = new byte[ripeHash.Length + 1]; extended[0] = network; Array.Copy(ripeHash, 0, extended, 1, ripeHash.Length); return extended; } private static byte[] ConcatAddress(byte[] ripeHash, byte[] checkSum) { var array = new byte[ripeHash.Length + 4]; Array.Copy(ripeHash, array, ripeHash.Length); Array.Copy(checkSum, 0, array, ripeHash.Length, 4); return array; } private static string Base58Encode(byte[] array) { const string Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; var result = string.Empty; BigInteger encodeSize = Alphabet.Length; BigInteger arrayToInt = 0; for (int i = 0; i < array.Length; ++i) { arrayToInt = arrayToInt * 256 + array[i]; } while (arrayToInt > 0) { var reminder = (int)(arrayToInt % encodeSize); arrayToInt /= encodeSize; result = Alphabet[reminder] + result; } for (int i = 0; i < array.Length && array[i] == 0; ++i) { result = Alphabet[0] + result; } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace AntColony { /// <summary> /// Interface for objects that are able to collide with complex colliders and want to be notified only when a collision with a /// unique complex collider has occured. /// </summary> public interface IComplexCollidable { GameObject gameObject { get; } /// <summary> /// Called whenever a collision with a unique complex collider occurs OR when a collision with a non-complex collider /// occurs. /// </summary> /// <param name="other">The collider that was contacted</param> void OnUniqueCollisionEnter(Collision collision); /// <summary> /// Called whenever a collision ends with a unique complex collider OR when a collision ends with a non-complex collider /// </summary> /// <param name="other">The collider that was exited</param> void OnUniqueCollisionExit(Collision collision); void OnUniqueTriggerEnter(Collider other); void OnUniqueTriggerExit(Collider other); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web; using System.Web.Http.Routing; namespace Millo.Constraints { public class EnumerationConstraint : IHttpRouteConstraint { private Type _enum { get; set; } public EnumerationConstraint(string type) { var t = GetType(type); if (t == null || !t.IsEnum) { throw new ArgumentException("Argument type is not Enum"); } _enum = t; } private static Type GetType(string typeName) { var t = Type.GetType(typeName); if (t != null) { return t; } foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) { t = a.GetType(typeName); if (t != null) { return t; } } return null; } public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection) { object value1; if (values.TryGetValue(parameterName, out value1) && value1 != null) { var stringVal = value1 as string; if (!string.IsNullOrEmpty(stringVal)) { stringVal = stringVal.ToLower(); if (null != _enum.GetEnumNames().FirstOrDefault(a => a.ToLower().Equals(stringVal))) { return true; } } } return false; } } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using System; namespace EnhancedEditor { /// <summary> /// Use this attribute on any <see cref="UnityEngine.Object"/> class to toggle its gizmos visibility. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class ScriptGizmosAttribute : EnhancedClassAttribute { #region Global Members /// <summary> /// Whether to display this script gizmos or not. /// </summary> public readonly bool ShowGizmos = true; /// <summary> /// Whether to display this script icon in the SceneView or not. /// </summary> public readonly bool ShowIcon = true; // ------------------------------------------- // Constructor(s) // ------------------------------------------- /// <param name="_showIcon"><inheritdoc cref="ShowIcon" path="/summary"/></param> /// <param name="_showGizmos"><inheritdoc cref="ShowGizmos" path="/summary"/></param> /// <inheritdoc cref="ScriptGizmosAttribute"/> public ScriptGizmosAttribute(bool _showIcon, bool _showGizmos = true) { ShowIcon = _showIcon; ShowGizmos = _showGizmos; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using ConcertGenerator.Models; using ConcertGenerator.Globals; using SQLite; namespace ConcertGenerator.Controllers { class PlayerApiController { public static void InitializeDatabase() { var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); path = Path.Combine(path, "ConcertGenerator.db3"); var db = new SQLiteConnection(path); db.CreateTable<Player>(); } public IEnumerable<Player> GetAllPlayers() { var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); path = Path.Combine(path, "ConcertGenerator.db3"); var db = new SQLiteConnection(path); return db.Table<Player>(); } public void AddNewPlayer(string playerName, List<InstrumentType> instruments) { var player = new Player { Name = playerName, //Instruments = instruments }; var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); path = Path.Combine(path, "ConcertGenerator.db3"); var db = new SQLiteConnection(path); db.Insert(player); } public void AddNewPlayer(Player newPlayer) { var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); path = Path.Combine(path, "ConcertGenerator.db3"); var db = new SQLiteConnection(path); db.Insert(newPlayer); } public void AddNewIntrumentToPlayer(string playerName,InstrumentType instrument) { var db = GetPlayerByName(playerName, out var player); if(player == null) return; // if (player.Instruments.Contains(instrument)) // return; //player.Instruments.Add(instrument); db.Update(player); } private static SQLiteConnection GetPlayerByName(string playerName, out Player player) { var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); path = Path.Combine(path, "ConcertGenerator.db3"); var db = new SQLiteConnection(path); player = db.Table<Player>().FirstOrDefault(s => s.Name == playerName); return db; } public void RemoveInstrumentFromPlayer(string playerName,InstrumentType instrument) { var db = GetPlayerByName(playerName, out var player); if(player==null) return; // if (!player.Instruments.Contains(instrument)) // return; // player.Instruments.Remove(instrument); db.Update(player); } public void RemoveAllInstrumentsFromPlayer(string playerName) { var db = GetPlayerByName(playerName, out var player); // player.Instruments.Clear(); db.Update(player); } public List<InstrumentType> GetAllInstrumentsFromPlayer(string playerName) { var db = GetPlayerByName(playerName, out var player); return null; // return player.Instruments; } } }
using System.Collections; using System.Collections.Generic; using System; using System.Text; public class Packet { private List<byte> _buffer = null; private ushort _offset = 0; public Packet() { this._buffer = new List<byte>(); this._offset = 0; } public Packet(byte[] bytes) { List<byte> buffer = new List<byte>(bytes); this._buffer = buffer; this._offset = 0; } public void Encode(ushort packetId) { List<byte> all = new List<byte>(); // 包体总长度 = (协议内容长度 + 协议号长度) PacketUtil.WriteUshort(all, (ushort)(this._buffer.Count + 2)); PacketUtil.WriteUshort(all, packetId); all.AddRange(this._buffer); this._buffer = all; } public List<byte> GetBuffer() { return this._buffer; } public byte[] GetBufferBytes() { return this._buffer.ToArray(); } public void WriteByte(byte v) { PacketUtil.WriteByte(this._buffer, v); } public void WriteSbyte(sbyte v) { PacketUtil.WriteSbyte(this._buffer, v); } public void WriteUshort(ushort v) { PacketUtil.WriteUshort(this._buffer, v); } public void WriteShort(short v) { PacketUtil.WriteShort(this._buffer, v); } public void WriteUint(uint v) { PacketUtil.WriteUint(this._buffer, v); } public void WriteInt(int v) { PacketUtil.WriteInt(this._buffer, v); } public void WriteUlong(ulong v) { PacketUtil.WriteUlong(this._buffer, v); } public void WriteLong(long v) { PacketUtil.WriteLong(this._buffer, v); } public void WriteFloat(float v) { PacketUtil.WriteFloat(this._buffer, v); } public void WriteDouble(double v) { PacketUtil.WriteDouble(this._buffer, v); } public void WriteString(string v) { PacketUtil.WriteString(this._buffer, v); } public void WriteBuffer(List<byte> buffer) { this._buffer.AddRange(buffer); } public byte ReadByte() { byte[] data = this._buffer.GetRange(this._offset, 1).ToArray(); this._offset+= 1; return PacketUtil.ReadByte(data); } public sbyte ReadSbyte() { byte[] data = this._buffer.GetRange(this._offset, 1).ToArray(); this._offset+= 1; return PacketUtil.ReadSbyte(data); } public ushort ReadUshort() { byte[] data = this._buffer.GetRange(this._offset, 2).ToArray(); this._offset+= 2; return PacketUtil.ReadUshort(data); } public short ReadShort() { byte[] data = this._buffer.GetRange(this._offset, 2).ToArray(); this._offset+= 2; return PacketUtil.ReadShort(data); } public uint ReadUint() { byte[] data = this._buffer.GetRange(this._offset, 4).ToArray(); this._offset += 4; return PacketUtil.ReadUint(data); } public int ReadInt() { byte[] data = this._buffer.GetRange(this._offset, 4).ToArray(); this._offset+= 4; return PacketUtil.ReadInt(data); } public ulong ReadUlong() { byte[] data = this._buffer.GetRange(this._offset, 8).ToArray(); this._offset+= 8; return PacketUtil.ReadUlong(data); } public long ReadLong() { byte[] data = this._buffer.GetRange(this._offset, 8).ToArray(); this._offset+= 8; return PacketUtil.ReadLong(data); } public float ReadFloat() { byte[] data = this._buffer.GetRange(this._offset, 4).ToArray(); this._offset+= 4; return PacketUtil.ReadFloat(data); } public double ReadDouble() { byte[] data = this._buffer.GetRange(this._offset, 8).ToArray(); this._offset+= 8; return PacketUtil.ReadDouble(data); } public string ReadString() { ushort len = this.ReadUshort(); byte[] data = this._buffer.GetRange(this._offset, len).ToArray(); this._offset+= len; return PacketUtil.ReadString(data); } }
using System; using System.Collections.Generic; #nullable disable namespace Crt.Data.Database.Entities { public partial class CrtRegion { public CrtRegion() { CrtProjects = new HashSet<CrtProject>(); CrtRegionDistricts = new HashSet<CrtRegionDistrict>(); CrtRegionUsers = new HashSet<CrtRegionUser>(); } public decimal RegionId { get; set; } public decimal RegionNumber { get; set; } public string RegionName { get; set; } public DateTime? EndDate { get; set; } public long ConcurrencyControlNumber { get; set; } public string DbAuditCreateUserid { get; set; } public DateTime DbAuditCreateTimestamp { get; set; } public string DbAuditLastUpdateUserid { get; set; } public DateTime DbAuditLastUpdateTimestamp { get; set; } public virtual ICollection<CrtProject> CrtProjects { get; set; } public virtual ICollection<CrtRegionDistrict> CrtRegionDistricts { get; set; } public virtual ICollection<CrtRegionUser> CrtRegionUsers { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RunAction : SSAction { // 移动速度和人物的transform private float speed; private Transform target; private Animator ani; public static RunAction GetRunAction(Transform target,float speed,Animator ani) { RunAction currentAction = ScriptableObject.CreateInstance<RunAction>(); currentAction.speed = speed; currentAction.target = target; currentAction.ani = ani; return currentAction; } public override void Start() { // 进入跑步状态 ani.SetFloat("Speed", 1); } public override void Update() { Quaternion rotation = Quaternion.LookRotation(target.position - transform.position); // 进行转向,转向目标方向 if (transform.rotation != rotation) transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * speed * 5); this.transform.position = Vector3.MoveTowards(this.transform.position, target.position, speed * Time.deltaTime); if (Vector3.Distance(this.transform.position, target.position) < 0.5) { this.destory = true; this.callback.SSEventAction(this); } } }
using AutoMapper; using FictionFantasyServer.Data.Entities; namespace FictionFantasyServer.Models.Mappings { public class NationalitiesProfile : Profile { public NationalitiesProfile() { CreateMap<Nationality, NationalitiesEntity>().ReverseMap(); } } }
//using System.Collections.Concurrent; //using System.Diagnostics; //using System.Runtime.InteropServices; //using System.Threading.Tasks; //using Discord; //using Discord.Audio; //using PlebBot.Helpers; //namespace PlebBot.Modules //{ // public class AudioService // { // private readonly ConcurrentDictionary<ulong, IAudioClient> _connectedChannels = new ConcurrentDictionary<ulong, IAudioClient>(); // public async Task JoinVoiceAsync(IGuild guild, IVoiceChannel channel) // { // IAudioClient client; // if (_connectedChannels.TryGetValue(guild.Id, out client)) return; // if (channel.Guild.Id != guild.Id) return; // var audioClient = await channel.ConnectAsync(); // _connectedChannels.TryAdd(guild.Id, audioClient); // } // public async Task LeaveVoiceAsync(IGuild guild) // { // IAudioClient client; // if (_connectedChannels.TryRemove(guild.Id, out client)) // await client.StopAsync(); // } // public async Task StreamAudioAsync(IGuild guild, string path) // { // IAudioClient client; // if (_connectedChannels.TryGetValue(guild.Id, out client)) // { // using (var output = CreateStream(path).StandardOutput.BaseStream) // using (var stream = client.CreatePCMStream(AudioApplication.Music)) // { // try { await output.CopyToAsync(stream); } // finally { await stream.FlushAsync(); } // } // } // } // public Task<string> ConvertToAudioAsync(string path) // { // Process process; // var audio = $"{path}.aac"; // //var args = $"-i \"{path}\" -q:a 0 -vn -ab 320k -ar 48000 -y \"{audio}\""; // var args = $"-y -i {path} -vn -ar 44100 -ac 2 -b:a 320 -f aac {audio}"; // if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) // { // process = Process.Start(new ProcessStartInfo() // { // FileName = "/bin/bash", // Arguments = $"ffmpeg {args}", // UseShellExecute = false, // RedirectStandardOutput = true // }); // } // else // { // process = Process.Start(new ProcessStartInfo() // { // FileName = "ffmpeg.exe", // Arguments = args, // UseShellExecute = false, // RedirectStandardOutput = true // }); // } // process?.WaitForExit(); // return Task.FromResult(audio); // } // public Task<bool> CheckIfInVoice(IGuild guild) // { // return Task.FromResult(_connectedChannels.TryGetValue(guild.Id, out IAudioClient client)); // } // private Process CreateStream(string path) // { // return Process.Start(new ProcessStartInfo // { // FileName = "ffmpeg.exe", // Arguments = $"-hide_banner -loglevel panic -i \"{path}\" -ac 2 -f s16le -ar 48000 pipe:1", // UseShellExecute = false, // RedirectStandardOutput = true // }); // } // } //}
using System; using System.Text; using System.Collections.Generic; using NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Exceptions; using LePapeoGenNHibernate.Exceptions; using LePapeoGenNHibernate.EN.LePapeo; using LePapeoGenNHibernate.CAD.LePapeo; /*PROTECTED REGION ID(usingLePapeoGenNHibernate.CEN.LePapeo_Reserva_crearReserva) ENABLED START*/ // references to other libraries /*PROTECTED REGION END*/ namespace LePapeoGenNHibernate.CEN.LePapeo { public partial class ReservaCEN { public int CrearReserva (int p_comensale, LePapeoGenNHibernate.Enumerated.LePapeo.EstadoReservaEnum p_estado, int p_registrado, int p_restaurante, bool p_finalizada, Nullable<DateTime> p_fecha_hora) { /*PROTECTED REGION ID(LePapeoGenNHibernate.CEN.LePapeo_Reserva_crearReserva) ENABLED START*/ RestauranteCAD restauranteCAD = new RestauranteCAD (); RestauranteEN restauranteEN = restauranteCAD.ReadOIDDefault (p_restaurante); int oid = 0; ReservaCEN reservaCEN = new ReservaCEN(); if ((restauranteEN.Max_comen - restauranteEN.Current_comen) >= p_comensale) { oid = reservaCEN.New_(p_registrado, p_restaurante, p_comensale, p_estado, p_finalizada, p_fecha_hora); restauranteEN.Current_comen += p_comensale; RestauranteCAD.Modify(restauranteEN); } return oid; /*PROTECTED REGION END*/ } } }
using System; using System.Collections.Generic; using System.Text; namespace GameOfLive { class Manual : IGame { public Cell[,] Method(Cell[,] PresentRound, int lenghtTotal) { int lenght = lenghtTotal - 2; for (int row = 0; row < lenghtTotal; row++) { for (int col = 0; col < lenghtTotal; col++) { PresentRound[row, col] = new Cell(row, col, false); } } int rowLlenar = 0; int colLlenar = 0; String s; do { Console.WriteLine("Introduce que fila y columna quieres llenar: "); rowLlenar = Convert.ToInt32(Console.ReadLine()); colLlenar = Convert.ToInt32(Console.ReadLine()); PresentRound[rowLlenar, colLlenar].State = true; Console.WriteLine("Quieres seguir introduciendo? "); s = Console.ReadLine(); } while (s.Equals("Si")); return PresentRound; } } }
// GENERATED CODE - DO NOT EDIT !!! using System.Collections.Generic; using CL.FormulaHelper; using CL.FormulaHelper.Attributes; using CL.FormulaHelper.DTOs; using System.Runtime.Serialization; namespace MeasureFormulas.Generated_Formula_Base_Classes { [FormulaBase] public abstract class ElectricDistributionReliabilityConsequenceBase : FormulaConsequenceBase { [DataContract] public class TimeInvariantInputDTO { public TimeInvariantInputDTO( System.Double? p_SystemCMI_32_cost_32__40__36__41_, System.Double? p_SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Mixed_32_Residential_44__32_Commercial_32_and_32_Industrial, System.Double? p_SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Purely_32_Commercial, System.Double? p_SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Residential, System.Double? p_SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_System_32_Average_32__47__32_Transmission, System.Double? p_SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Mixed_32_Residential_44__32_Commercial_32_and_32_Industrial, System.Double? p_SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Purely_32_Commercial, System.Double? p_SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Residential, System.Double? p_SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_System_32_Average_32__47__32_Transmission, CL.FormulaHelper.DTOs.CustomFieldListItemDTO p_Type_32_of_32_Load) { SystemCMI_32_cost_32__40__36__41_ = p_SystemCMI_32_cost_32__40__36__41_; SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Mixed_32_Residential_44__32_Commercial_32_and_32_Industrial = p_SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Mixed_32_Residential_44__32_Commercial_32_and_32_Industrial; SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Purely_32_Commercial = p_SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Purely_32_Commercial; SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Residential = p_SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Residential; SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_System_32_Average_32__47__32_Transmission = p_SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_System_32_Average_32__47__32_Transmission; SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Mixed_32_Residential_44__32_Commercial_32_and_32_Industrial = p_SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Mixed_32_Residential_44__32_Commercial_32_and_32_Industrial; SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Purely_32_Commercial = p_SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Purely_32_Commercial; SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Residential = p_SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Residential; SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_System_32_Average_32__47__32_Transmission = p_SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_System_32_Average_32__47__32_Transmission; Type_32_of_32_Load = p_Type_32_of_32_Load; } [CustomFieldInput("CMI cost ($)", FormulaInputAssociatedEntity.System)] [DataMember] public System.Double? SystemCMI_32_cost_32__40__36__41_ { get; private set; } [CustomFieldInput("Duration Cost ($/kWh) - Mixed Residential, Commercial and Industrial", FormulaInputAssociatedEntity.System)] [DataMember] public System.Double? SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Mixed_32_Residential_44__32_Commercial_32_and_32_Industrial { get; private set; } [CustomFieldInput("Duration Cost ($/kWh) - Purely Commercial", FormulaInputAssociatedEntity.System)] [DataMember] public System.Double? SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Purely_32_Commercial { get; private set; } [CustomFieldInput("Duration Cost ($/kWh) - Residential", FormulaInputAssociatedEntity.System)] [DataMember] public System.Double? SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_Residential { get; private set; } [CustomFieldInput("Duration Cost ($/kWh) - System Average / Transmission", FormulaInputAssociatedEntity.System)] [DataMember] public System.Double? SystemDuration_32_Cost_32__40__36__47_kWh_41__32__45__32_System_32_Average_32__47__32_Transmission { get; private set; } [CustomFieldInput("Frequency Cost ($/kW) - Mixed Residential, Commercial and Industrial", FormulaInputAssociatedEntity.System)] [DataMember] public System.Double? SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Mixed_32_Residential_44__32_Commercial_32_and_32_Industrial { get; private set; } [CustomFieldInput("Frequency Cost ($/kW) - Purely Commercial", FormulaInputAssociatedEntity.System)] [DataMember] public System.Double? SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Purely_32_Commercial { get; private set; } [CustomFieldInput("Frequency Cost ($/kW) - Residential", FormulaInputAssociatedEntity.System)] [DataMember] public System.Double? SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_Residential { get; private set; } [CustomFieldInput("Frequency Cost ($/kW) - System Average / Transmission", FormulaInputAssociatedEntity.System)] [DataMember] public System.Double? SystemFrequency_32_Cost_32__40__36__47_kW_41__32__45__32_System_32_Average_32__47__32_Transmission { get; private set; } [PromptInput("Type of Load")] [DataMember] public CL.FormulaHelper.DTOs.CustomFieldListItemDTO Type_32_of_32_Load { get; private set; } } [DataContract] public class TimeVariantInputDTO : ITimeVariantInputDTO { public TimeVariantInputDTO( System.Double p_Annual_32_Failure_32_Frequency, System.Double p_Lost_32_Redundancy_32_Duration, System.Int32 p_Number_32_of_32_Customers_32_Impacted, System.Double p_Outage_32_Duration, System.Double? p_Peak_32_Lost_32_Load, CL.FormulaHelper.DTOs.TimePeriodDTO p_TimePeriod) { Annual_32_Failure_32_Frequency = p_Annual_32_Failure_32_Frequency; Lost_32_Redundancy_32_Duration = p_Lost_32_Redundancy_32_Duration; Number_32_of_32_Customers_32_Impacted = p_Number_32_of_32_Customers_32_Impacted; Outage_32_Duration = p_Outage_32_Duration; Peak_32_Lost_32_Load = p_Peak_32_Lost_32_Load; TimePeriod = p_TimePeriod; } [PromptInput("Annual Failure Frequency")] [DataMember] public System.Double Annual_32_Failure_32_Frequency { get; private set; } [PromptInput("Lost Redundancy Duration")] [DataMember] public System.Double Lost_32_Redundancy_32_Duration { get; private set; } [PromptInput("Number of Customers Impacted")] [DataMember] public System.Int32 Number_32_of_32_Customers_32_Impacted { get; private set; } [PromptInput("Outage Duration")] [DataMember] public System.Double Outage_32_Duration { get; private set; } [PromptInput("Peak Lost Load")] [DataMember] public System.Double? Peak_32_Lost_32_Load { get; private set; } [CoreFieldInput(FormulaCoreFieldInputType.TimePeriod)] [DataMember] public CL.FormulaHelper.DTOs.TimePeriodDTO TimePeriod { get; private set; } } public abstract double?[] GetUnits(int startFiscalYear, int months, TimeInvariantInputDTO timeInvariantData, IReadOnlyList<TimeVariantInputDTO> timeVariantData); public abstract double?[] GetZynos(int startFiscalYear, int months, TimeInvariantInputDTO timeInvariantData, IReadOnlyList<TimeVariantInputDTO> timeVariantData, double?[] unitOutput); /// /// Class to enable formula debugging /// [DataContract] public class FormulaParams : IFormulaParams { public FormulaParams(CL.FormulaHelper.MeasureOutputType measureOutputType, string measureName, long alternativeId, string formulaImplClassName, bool isProbabilityFormula, int fiscalYearEndMonth, int startFiscalYear, int months, TimeInvariantInputDTO timeInvariantData, IReadOnlyList<TimeVariantInputDTO> timeVariantData, double?[] unitOutput, double?[] formulaOutput, string exceptionMessage) { MeasureOutputType = measureOutputType; MeasureName = measureName; AlternativeId = alternativeId; FormulaImplClassName = formulaImplClassName; IsProbabilityFormula = isProbabilityFormula; FiscalYearEndMonth = fiscalYearEndMonth; StartFiscalYear = startFiscalYear; Months = months; TimeInvariantData = timeInvariantData; TimeVariantData = timeVariantData; UnitOutput = unitOutput; FormulaOutput = formulaOutput; ExceptionMessage = exceptionMessage; } [DataMember(Order = 0)] public CL.FormulaHelper.MeasureOutputType MeasureOutputType { get; set; } [DataMember(Order = 1)] public string MeasureName { get; set; } [DataMember(Order = 2)] public long AlternativeId { get; set; } [DataMember(Order = 3)] public string FormulaImplClassName { get; set; } [DataMember(Order = 4)] public bool IsProbabilityFormula { get; set; } [DataMember(Order = 5)] public int FiscalYearEndMonth { get; set; } [DataMember(Order = 6)] public int StartFiscalYear { get; set; } [DataMember(Order = 7)] public int Months { get; set; } [DataMember(Order = 8)] public TimeInvariantInputDTO TimeInvariantData { get; set; } [DataMember(Order = 9)] public IReadOnlyList<TimeVariantInputDTO> TimeVariantData { get; set; } [DataMember(Order = 10)] public double?[] UnitOutput { get; set; } [DataMember(Order = 11)] public double?[] FormulaOutput { get; set; } [DataMember(Order = 12)] public string ExceptionMessage { get; set; } } } } // GENERATED CODE - DO NOT EDIT !!!
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace SGDE.DataEFCoreSQL.Migrations { public partial class Add_Table_DetailEmbargo : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "AccountNumber", table: "Embargo", nullable: true); migrationBuilder.CreateTable( name: "DetailEmbargo", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), AddedDate = table.Column<DateTime>(nullable: true), ModifiedDate = table.Column<DateTime>(nullable: true), IPAddress = table.Column<string>(nullable: true), DatePay = table.Column<DateTime>(nullable: false), Observations = table.Column<string>(nullable: true), Amount = table.Column<decimal>(type: "decimal(18,2)", nullable: false), EmbargoId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_DetailEmbargo", x => x.Id); table.ForeignKey( name: "FK__DetailEmbargo__EmbargoId", column: x => x.EmbargoId, principalTable: "Embargo", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IFK_Embargo_DetailEmbargo", table: "DetailEmbargo", column: "EmbargoId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "DetailEmbargo"); migrationBuilder.DropColumn( name: "AccountNumber", table: "Embargo"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Project3.Classes.Sorting { public sealed class HeapSort : SortingBase { public HeapSort() { Name = "Heap Sort"; } private void Heapify(int[] t, int left, int right) { int i = left, j = 2 * i + 1; int buf = t[i]; while (j <= right) { if (j < right) if (t[j] < t[j + 1]) j++; if (buf >= t[j]) break; t[i] = t[j]; i = j; j = 2 * i + 1; } t[i] = buf; } public override void Sort(int[] arr) { int left = (int)arr.Length / 2; int right = (int)arr.Length - 1; while (left > 0) { left--; Heapify(arr, left, right); } while (right > 0) { int buf = arr[left]; arr[left] = arr[right]; arr[right] = buf; right--; Heapify(arr, left, right); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; public partial class Login : System.Web.UI.Page { private SqlConnection SQLBaglantiAc() { SqlConnection baglan = new SqlConnection(ConfigurationManager.ConnectionStrings["Baglanti"].ConnectionString); try { if (baglan.State==ConnectionState.Closed) { baglan.Open(); } } catch (Exception e) { lbl_error.Visible = true; lbl_error.Text = e.ToString(); } return baglan; } private void SQLBaglantiKapat(SqlConnection dbBaglanti) { try { if (dbBaglanti.State == ConnectionState.Open) { dbBaglanti.Close(); dbBaglanti.Dispose(); } } catch (Exception e) { lbl_error.Visible = true; lbl_error.Text = e.ToString(); } } protected void Page_Load(object sender, EventArgs e) { lbl_error.Visible = false; HttpCookie CookieGetir = Request.Cookies["SiteLogin"]; if (CookieGetir != null) { Session["userid"] = CookieGetir["userid"]; Session["id"] = CookieGetir["id"]; Response.Redirect("~/ChatRooms.aspx"); } } protected void btn_giris_Click(object sender, EventArgs e) { lbl_error.Visible = false; try { SqlCommand UserKontrol = new SqlCommand("exec RunLogin '" + txt_userid.Value + "', '" + txt_password.Value + "'", SQLBaglantiAc()); SqlDataReader OkuUserID = UserKontrol.ExecuteReader(); while (OkuUserID.Read()) { if (Convert.ToInt32(OkuUserID["say"]) > 0 && Convert.ToInt32(OkuUserID["izin"]) > 0) { Session.Add("userid", txt_userid.Value); Session.Add("logDate", DateTime.Now); string _id = OkuUserID["id"].ToString(); Session.Add("id", _id); if (check_beni_hatirla.Checked) { HttpCookie CookieLogin = new HttpCookie("SiteLogin"); CookieLogin["userid"] = txt_userid.Value; CookieLogin["id"] = _id; Response.Cookies.Add(CookieLogin); Response.Cookies["SiteLogin"].Expires = DateTime.Now.AddDays(7); } SqlCommand LogEkle = new SqlCommand("declare @datetime datetime = getdate() exec AddLog '" + Session["userid"].ToString() + "',@datetime,'I'", SQLBaglantiAc()); LogEkle.ExecuteNonQuery(); SQLBaglantiKapat(SQLBaglantiAc()); Response.Redirect("~/ChatRooms.aspx"); } else { lbl_error.Visible = true; lbl_error.Text = OkuUserID["durum"].ToString(); } } } catch (Exception hata) { lbl_error.Visible = true; lbl_error.Text = hata.ToString(); } } protected void btn_Kaydol_Click(object sender, EventArgs e) { Response.Redirect("~/Register.aspx"); } protected void btn_sifremi_unuttum_Click(object sender, EventArgs e) { } }