text stringlengths 13 6.01M |
|---|
using System.IO;
namespace LogsSearchServer.Models
{
public class FoundFile
{
public string Name { get; set; }
public string FullPath { get; set; }
public long Size { get; set; }
public FoundFile()
{
}
public FoundFile(string fullPath)
{
Name = Path.GetFileName(fullPath);
FullPath = fullPath;
Size = (new FileInfo(fullPath)).Length;
}
}
} |
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;
namespace EurekaQuiz
{
public partial class FrmAlterarCadPessoa : Form
{
public FrmAlterarCadPessoa()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
// Display a message box asking users if they
// want to exit the application.
if (MessageBox.Show("Deseja realmente sair?", "Eureka Quiz",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.Yes)
{
try
{
//Esconda o formulario atual
this.Hide();
// Crie apenas o segundo form
FrmTelaInicio frmTelaInicio = new FrmTelaInicio();
//Mostre o segundo form
frmTelaInicio.ShowDialog();
}
finally
{
// ao fechar, mostre novamente o inicial, ou feche this.Close();
this.Show();
}
}
}
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
[Attribute38("MobileChatLogMessageFrame")]
public class MobileChatLogMessageFrame : MonoBehaviour
{
public MobileChatLogMessageFrame(IntPtr address) : this(address, "MobileChatLogMessageFrame")
{
}
public MobileChatLogMessageFrame(IntPtr address, string className) : base(address, className)
{
}
public void UpdateLocalBounds()
{
base.method_8("UpdateLocalBounds", Array.Empty<object>());
}
public Triton.Game.Mapping.Color Color
{
get
{
return base.method_11<Triton.Game.Mapping.Color>("get_Color", Array.Empty<object>());
}
}
public bool IsHeader
{
get
{
return base.method_11<bool>("get_IsHeader", Array.Empty<object>());
}
}
public Bounds localBounds
{
get
{
return base.method_2<Bounds>("localBounds");
}
}
public Bounds LocalBounds
{
get
{
return base.method_11<Bounds>("get_LocalBounds", Array.Empty<object>());
}
}
public GameObject m_Background
{
get
{
return base.method_3<GameObject>("m_Background");
}
}
public string Message
{
get
{
return base.method_13("get_Message", Array.Empty<object>());
}
}
public UberText text
{
get
{
return base.method_3<UberText>("text");
}
}
public bool Visible
{
get
{
return base.method_11<bool>("get_Visible", Array.Empty<object>());
}
}
public float Width
{
get
{
return base.method_11<float>("get_Width", Array.Empty<object>());
}
}
}
}
|
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Redis.Cache.Sample.Services.MemoryCache
{
public class MemoryCacheService : IMemoryCacheService
{
private IMemoryCache _memoryCache;
public MemoryCacheService(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public Task<T> GetValue<T>(string key)
{
if (_memoryCache.TryGetValue(key, out T cacheEntry))
{
return Task.FromResult(cacheEntry);
}
return Task.FromResult<T>(default);
}
public Task RemoveValue(string key)
{
_memoryCache.Remove(key);
return Task.CompletedTask;
}
public Task SetValue<T>(string key, T value)
{
_memoryCache.Set(key, value);
return Task.CompletedTask;
}
public Task SetValue<T>(string key, T value, TimeSpan expirationTimeSpan)
{
_memoryCache.Set(key, value, expirationTimeSpan);
return Task.CompletedTask;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using MyListApp;
namespace MyListApp_5
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SettingsPage : ContentPage
{
public SettingsPage()
{
InitializeComponent();
MessagingCenter.Subscribe<SyncManager>(this, SyncManager.Syncing, (sender) =>
{
Device.BeginInvokeOnMainThread(() =>
{
indicator.IsVisible = true;
indicator.IsRunning = true;
});
});
MessagingCenter.Subscribe<SyncManager>(this, SyncManager.Synced, (sender) =>
{
Device.BeginInvokeOnMainThread(() =>
{
indicator.IsVisible = false;
indicator.IsRunning = false;
statusLabel.TextColor = Color.Green;
statusLabel.Text = "Synced";
});
});
MessagingCenter.Subscribe<SyncManager>(this, SyncManager.NotSynced, (sender) =>
{
Device.BeginInvokeOnMainThread(() =>
{
indicator.IsVisible = false;
indicator.IsRunning = false;
statusLabel.TextColor = Color.Red;
statusLabel.Text = "Not Synced";
});
});
MessagingCenter.Subscribe<SyncManager>(this, SyncManager.LoggedIn, (sender) =>
{
Device.BeginInvokeOnMainThread(() =>
{
indicator.IsVisible = false;
indicator.IsRunning = false;
statusLabel.TextColor = Color.Green;
statusLabel.Text = "Logged In OK";
});
});
MessagingCenter.Subscribe<SyncManager>(this, SyncManager.NotLoggedIn, (sender) =>
{
Device.BeginInvokeOnMainThread(() =>
{
indicator.IsVisible = false;
indicator.IsRunning = false;
statusLabel.TextColor = Color.Red;
statusLabel.Text = "Logged In Error";
});
});
}
private void SaveButton_Clicked(object sender, EventArgs e)
{
// TODO Validate
User user = new User();
user.FirstName = firstNameEntry.Text;
user.Surname = surnameNameEntry.Text;
user.UserName = userNameEntry.Text;
user.Password = passwordEntry.Text;
user.ServerURL = serverURLEntry.Text;
IsValidServer(user.ServerURL); // could use as test
// Login
WebServices.Login(serverURLEntry.Text, userNameEntry.Text, passwordEntry.Text);
// REST Service
//WebServices.GetList<Property>(serverURLEntry.Text, userNameEntry.Text, passwordEntry.Text);
Model.Users.Clear();
Model.Users.Add(user);
Database.SaveModel();
}
bool IsValidServer(String url)
{
if (WebServices.IsServerAvailable(url))
{
statusLabel.TextColor = Color.Green;
statusLabel.Text = "Server Available";
return true;
}
else
{
statusLabel.TextColor = Color.Red;
statusLabel.Text = "Server Not Available";
return false;
}
}
// Use to load saved user
protected override void OnAppearing()
{
base.OnAppearing();
if (Model.Users.Count > 0)
{
firstNameEntry.Text = Model.Users[0].FirstName;
surnameNameEntry.Text = Model.Users[0].Surname;
userNameEntry.Text = Model.Users[0].UserName;
passwordEntry.Text = Model.Users[0].Password;
serverURLEntry.Text = Model.Users[0].ServerURL;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace poiLoader
{
class account
{
public string profileName { get; set; }
public string userName { get; set; }
public string password { get; set; }
public string SteamPath { get; set; }
public account(string profile, string user, string pass, string path)
{
this.profileName = profile;
this.userName = user;
this.password = pass;
this.SteamPath = path;
}
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Apix.Sync.YaMarket.Models
{
public class Region
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "childCount")]
public int ChildCount { get; set; }
[JsonProperty(PropertyName = "country")]
public int Country { get; set; }
}
public class Currency
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
public class Page
{
[JsonProperty(PropertyName = "number")]
public int Number { get; set; }
[JsonProperty(PropertyName = "count")]
public int Count { get; set; }
[JsonProperty(PropertyName = "total")]
public int Total { get; set; }
}
public class ProcessingOptions
{
[JsonProperty(PropertyName = "adult")]
public bool Adult { get; set; }
}
public class Context
{
[JsonProperty(PropertyName = "region")]
public Region Region { get; set; }
[JsonProperty(PropertyName = "currency")]
public Currency Currency { get; set; }
[JsonProperty(PropertyName = "page")]
public Page Page { get; set; }
[JsonProperty(PropertyName = "processingOptions")]
public ProcessingOptions ProcessingOptions { get; set; }
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "time")]
public string Time { get; set; }
}
public class Price
{
[JsonProperty(PropertyName = "value")]
public string Value { get; set; }
}
public class Status
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
public class Rating
{
[JsonProperty(PropertyName = "value")]
public string Value { get; set; }
[JsonProperty(PropertyName = "count")]
public int Count { get; set; }
[JsonProperty(PropertyName = "status")]
public Status Status { get; set; }
}
public class Shop
{
[JsonProperty(PropertyName = "region")]
public Region Region { get; set; }
[JsonProperty(PropertyName = "rating")]
public Rating Rating { get; set; }
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "domain")]
public string Domain { get; set; }
[JsonProperty(PropertyName = "registered")]
public string Registered { get; set; }
}
public class Model
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
}
public class Phone
{
[JsonProperty(PropertyName = "number")]
public string Number { get; set; }
[JsonProperty(PropertyName = "sanitized")]
public string Sanitized { get; set; }
[JsonProperty(PropertyName = "call")]
public string Call { get; set; }
}
public class ShopRegion
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "nameRuGenitive")]
public string NameRuGenitive { get; set; }
[JsonProperty(PropertyName = "nameRuAccusative")]
public string NameRuAccusative { get; set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "childCount")]
public int ChildCount { get; set; }
[JsonProperty(PropertyName = "country")]
public int Country { get; set; }
}
public class UserRegion
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "childCount")]
public int ChildCount { get; set; }
[JsonProperty(PropertyName = "country")]
public int Country { get; set; }
}
public class Service
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
}
public class Option
{
[JsonProperty(PropertyName = "service")]
public Service Service { get; set; }
}
public class Conditions
{
[JsonProperty(PropertyName = "price")]
public Price Price { get; set; }
[JsonProperty(PropertyName = "daysFrom")]
public int DaysFrom { get; set; }
[JsonProperty(PropertyName = "daysTo")]
public int DaysTo { get; set; }
}
public class LocalOption
{
[JsonProperty(PropertyName = "conditions")]
public Conditions Conditions { get; set; }
[JsonProperty(PropertyName = "@default")]
public bool Default { get; set; }
}
public class Delivery
{
[JsonProperty(PropertyName = "price")]
public Price Price { get; set; }
[JsonProperty(PropertyName = "free")]
public bool Free { get; set; }
[JsonProperty(PropertyName = "deliveryIncluded")]
public bool DeliveryIncluded { get; set; }
[JsonProperty(PropertyName = "carried")]
public bool Carried { get; set; }
[JsonProperty(PropertyName = "pickup")]
public bool Pickup { get; set; }
[JsonProperty(PropertyName = "downloadable")]
public bool Downloadable { get; set; }
[JsonProperty(PropertyName = "localStore")]
public bool LocalStore { get; set; }
[JsonProperty(PropertyName = "localDelivery")]
public bool LocalDelivery { get; set; }
[JsonProperty(PropertyName = "shopRegion")]
public ShopRegion ShopRegion { get; set; }
[JsonProperty(PropertyName = "userRegion")]
public UserRegion UserRegion { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "brief")]
public string Brief { get; set; }
[JsonProperty(PropertyName = "inStock")]
public bool InStock { get; set; }
[JsonProperty(PropertyName = "options")]
public List<Option> Options { get; set; }
[JsonProperty(PropertyName = "localOptions")]
public List<LocalOption> LocalOptions { get; set; }
}
public class Vendor
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "site")]
public string Site { get; set; }
[JsonProperty(PropertyName = "picture")]
public string Picture { get; set; }
[JsonProperty(PropertyName = "link")]
public string Link { get; set; }
}
public class PaymentOptions
{
[JsonProperty(PropertyName = "canPayByCard")]
public bool CanPayByCard { get; set; }
}
public class BigPhoto
{
[JsonProperty(PropertyName = "width")]
public int Width { get; set; }
[JsonProperty(PropertyName = "height")]
public int Height { get; set; }
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
}
public class Photo
{
[JsonProperty(PropertyName = "width")]
public int Width { get; set; }
[JsonProperty(PropertyName = "height")]
public int Height { get; set; }
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
}
public class PreviewPhoto
{
[JsonProperty(PropertyName = "width")]
public int Width { get; set; }
[JsonProperty(PropertyName = "height")]
public int Height { get; set; }
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
}
public class Offer
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "wareMd5")]
public string WareMd5 { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "price")]
public Price Price { get; set; }
[JsonProperty(PropertyName = "cpa")]
public bool Cpa { get; set; }
[JsonProperty(PropertyName = "url")]
public string Url { get; set; }
[JsonProperty(PropertyName = "shop")]
public Shop Shop { get; set; }
[JsonProperty(PropertyName = "model")]
public Model Model { get; set; }
[JsonProperty(PropertyName = "onStock")]
public bool OnStock { get; set; }
[JsonProperty(PropertyName = "phone")]
public Phone Phone { get; set; }
[JsonProperty(PropertyName = "delivery")]
public Delivery Delivery { get; set; }
[JsonProperty(PropertyName = "vendor")]
public Vendor Vendor { get; set; }
[JsonProperty(PropertyName = "warranty")]
public bool Warranty { get; set; }
[JsonProperty(PropertyName = "recommended")]
public bool Recommended { get; set; }
[JsonProperty(PropertyName = "link")]
public string Link { get; set; }
[JsonProperty(PropertyName = "variationCount")]
public int VariationCount { get; set; }
[JsonProperty(PropertyName = "paymentOptions")]
public PaymentOptions PaymentOptions { get; set; }
[JsonProperty(PropertyName = "bigPhoto")]
public BigPhoto BigPhoto { get; set; }
[JsonProperty(PropertyName = "photos")]
public List<Photo> Photos { get; set; }
[JsonProperty(PropertyName = "previewPhotos")]
public List<PreviewPhoto> PreviewPhotos { get; set; }
[JsonProperty(PropertyName = "cpaUrl")]
public string CpaUrl { get; set; }
}
public class OffersResult
{
[JsonProperty(PropertyName = "status")]
public string Status { get; set; }
[JsonProperty(PropertyName = "context")]
public Context Context { get; set; }
[JsonProperty(PropertyName = "offers")]
public List<Offer> Offers { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using AutoMapper;
namespace Dentist.Models.Doctor
{
public class Qualification : IValidatableObject
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
[StringLength(100)]
public string College { get; set; }
[Required]
public int Year { get; set; }
[Required]
public int DoctorId { get; set; }
public virtual Models.Doctor.Doctor Doctor { get; set; }
public override bool Equals(object obj)
{
var qualification = (Qualification) obj;
return this.Name == qualification.Name &&
this.College == qualification.College &&
this.Year == qualification.Year;
}
public override int GetHashCode()
{
return this.Name.GetHashCode() ^ this.College.GetHashCode() ^ this.Year.GetHashCode();
}
[NotMapped]
public WriteContext Context { get; set; }
public bool HasDuplicateQualification()
{
// if distinct qualifications are same as non distinct qualification that means there is no repeated qualification with same name, college, year
// Note that distinct make use of Equals method to get unique names
return this.Doctor.Qualifications.Distinct().Count() != this.Doctor.Qualifications.Count();
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Context == null)
{
throw new Exception("Context missing in Qualification");
}
var results = new List<ValidationResult>();
// Lazy loading is turned off by EF during validation therefore load the doctor manually
if (!Context.Entry(this).Reference(p => p.Doctor).IsLoaded)
{
Context.Entry(this).Reference(p => p.Doctor).Load();
this.Doctor.Context = Context;
}
if (this.Doctor.Qualifications.Count > 1)
{
if (HasDuplicateQualification())
{
results.Add(new ValidationResult("Qualification cannot be repeated"));
}
}
return results;
}
}
} |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using System;
using System.Collections.Generic;
namespace FirstAndroidMonoGame
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
MovingSprite sprite;
SpriteFont font;
float spriteGrowSpeed;
byte rColorChange, gColorChange, bColorChange;
KeyboardState ks;
TouchCollection touch;
Vector2 spriteSpeed;
List<ParticleSprite> particles;
TimeSpan generateSpriteTime;
TimeSpan elapsedTime;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.IsFullScreen = true;
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 480;
graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
sprite = new MovingSprite(Content.Load<Texture2D>("WhitePixel"), new Vector2(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2), Color.White);
//sprite.Position = Vector2.Zero;
sprite.Scale = new Vector2(300 * GraphicsDevice.Viewport.Height / 1440f, 300 * GraphicsDevice.Viewport.Height / 1440f);
sprite.SetCenterOrigin();
spriteGrowSpeed = 2;
font = Content.Load<SpriteFont>("Font");
rColorChange = 1;
gColorChange = 1;
bColorChange = 1;
sprite.Color = new Color(100, 255, 255);
spriteSpeed = Vector2.Zero;
particles = new List<ParticleSprite>();
generateSpriteTime = TimeSpan.FromMilliseconds(20);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
ks = Keyboard.GetState();
touch = TouchPanel.GetState();
if (touch.Count > 0 && touch[0].State == TouchLocationState.Moved)
{
spriteSpeed = touch[0].Position - sprite.Position;
spriteSpeed.X /= 12;
spriteSpeed.Y /= 12;
sprite.Speed = spriteSpeed;
sprite.Update(gameTime);
elapsedTime += gameTime.ElapsedGameTime;
if(elapsedTime >= generateSpriteTime && spriteSpeed.Length() > 0.005f)
{
particles.Add(new ParticleSprite(Content.Load<Texture2D>("WhitePixel"), sprite.Position, sprite.Color, spriteSpeed, 15, 40, TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(2000)));
elapsedTime = new TimeSpan();
}
}
for(int i = 0; i < particles.Count; i++)
{
particles[i].Update(gameTime);
if(particles[i].Dead)
{
particles.Remove(particles[i]);
i--;
}
}
sprite.Rotation += .025f;
sprite.Scale = new Vector2(sprite.Scale.X + spriteGrowSpeed, sprite.Scale.Y + spriteGrowSpeed);
if (sprite.Scale.X >= 310 * GraphicsDevice.Viewport.Height / 1440f || sprite.Scale.X <= 100 * GraphicsDevice.Viewport.Height / 1440f)
{
spriteGrowSpeed = -spriteGrowSpeed;
}
if (sprite.Color.R < 255 && sprite.Color.G == 0 && sprite.Color.B == 0)
{
sprite.Color = new Color(sprite.Color.R + rColorChange, sprite.Color.G, sprite.Color.B);
}
else if (sprite.Color.R == 255 && sprite.Color.G < 255 && sprite.Color.B == 0)
{
sprite.Color = new Color(sprite.Color.R, sprite.Color.G + gColorChange, sprite.Color.B);
}
else if (sprite.Color.R == 255 && sprite.Color.G == 255 && sprite.Color.B < 255)
{
sprite.Color = new Color(sprite.Color.R, sprite.Color.G, sprite.Color.B + bColorChange);
}
else if (sprite.Color.R > 0 && sprite.Color.G == 255 && sprite.Color.B == 255)
{
sprite.Color = new Color(sprite.Color.R - rColorChange, sprite.Color.G, sprite.Color.B);
}
else if (sprite.Color.R == 0 && sprite.Color.G > 0 && sprite.Color.B == 255)
{
sprite.Color = new Color(sprite.Color.R, sprite.Color.G - gColorChange, sprite.Color.B);
}
else if (sprite.Color.R == 0 && sprite.Color.G == 0 && sprite.Color.B > 0)
{
sprite.Color = new Color(sprite.Color.R, sprite.Color.G, sprite.Color.B - bColorChange);
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.MistyRose);
spriteBatch.Begin(); foreach (ParticleSprite particle in particles)
{
particle.Draw(spriteBatch);
}
sprite.Draw(spriteBatch);
spriteBatch.DrawString(font, touch.Count.ToString(), Vector2.Zero, Color.White,0f, Vector2.Zero, 5f, SpriteEffects.None, 1f);
if(touch.Count > 0)
{
spriteBatch.DrawString(font, touch[0].State.ToString(), new Vector2(0, 50), Color.White, 0f, Vector2.Zero, 5f, SpriteEffects.None, 1f);
}
spriteBatch.DrawString(font, spriteSpeed.Length().ToString(), new Vector2(0, 100), Color.White, 0f, Vector2.Zero, 5f, SpriteEffects.None, 1f);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
|
using CoffeeFinder.Views;
using Xamarin.Forms;
namespace CoffeeFinder
{
public static class GlobalVariables
{
public static double unitchange = 1609.34;
public static string selected_website = "";
public static string selected_call = "";
}
public class App : Application
{
public App ()
{
// The root page of your application
MainPage = new NavigationPage(new MainView());
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entidades;
namespace Archivos
{
public class Texto : IArchivo<Queue<Patente>>
{
public void Guardar(string archivo, Queue<Patente> datos)
{
StreamWriter sw = new StreamWriter(archivo, true);
foreach (Patente p in datos)
{
sw.WriteLine(p.ToString());
}
sw.Close();
}
public void Leer(string archivo, out Queue<Patente> datos)
{
StreamReader sr = new StreamReader(archivo);
Patente aux;
String patente = "";
datos = new Queue<Patente>();
while (!(sr.EndOfStream))
{
patente = sr.ReadLine();
aux = patente.MetodoExtendido();
datos.Enqueue(aux);
}
sr.Close();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace CL_UWP.SpeechClasses
{
//public static class PhrTiming
//{
// private static TimeSpan tsElapsed;
// public static TimeSpan TsElapsed
// {
// get { return tsElapsed; }
// set { tsElapsed = value; }
// }
//}
public static class PHRMediaElementExtensions
{
public static async Task PrompterPlayStreamAsync(
this MediaElement mediaElement,
IRandomAccessStream stream,
bool disposeStream = true)
{
// bool is irrelevant here, just using this to flag task completion.
TaskCompletionSource<bool> taskCompleted = new TaskCompletionSource<bool>();
// Note that the MediaElement needs to be in the UI tree for events
// like MediaEnded to fire.
RoutedEventHandler endOfPlayHandler = (s, e) =>
{
if (disposeStream)
{
stream.Dispose();
}
taskCompleted.SetResult(true);
};
mediaElement.MediaEnded += endOfPlayHandler;
mediaElement.SetSource(stream, string.Empty);
mediaElement.Play();
#region TODO: Maybe Get sender/caller
//RepeaterUserControl repeaterUC = new RepeaterUserControl();
//RepeaterUserControl2 repeaterUC2 = new RepeaterUserControl2();
////QnAPage qnAPage = new QnAPage();
//if (repeaterUC2.MySender == "BtnRepeatMediaOutAsync2")
//{
// Debug.WriteLine("Sender is RepeaterUserControl: " + repeaterUC2.MySender.ToString());
//}
//else if(repeaterUC2.MySender == "BtnRepeatMediaOutAsync2")
//{
// Debug.WriteLine("Sender is RepeaterUserControl2: " + repeaterUC2.MySender.ToString());
//}
//else
//{
// Debug.WriteLine("Sender undetermined");
//}
#endregion
//Code-Set Get Amount of time takes for Async Task - await takes
//PhrTiming phrTiming = new PhrTiming();
Int32 secs = 0;
Int32 secs2 = 0;
PhRTiming.TsElapsed = new TimeSpan(0, 0, secs);
var sw = new Stopwatch();
sw.Start();
try
{
bool IsValid = await taskCompleted.Task;
//Debug.WriteLine("\nbool IsValid : " + IsValid.ToString());
}
catch (Exception) { }
try
{
sw.Stop();
PhRTiming.TsElapsed = sw.Elapsed;
Debug.WriteLine("sw.Elapsed before Rest: " + sw.Elapsed.ToString());
sw.Reset();
// PhrTiming.TsElapsed = sw.Elapsed;
Debug.WriteLine("sw.Elapsed after Rest: " + sw.Elapsed.ToString());
Debug.WriteLine("\n\nElapsed Seconds: " + PhRTiming.TsElapsed.Seconds.ToString());
Debug.WriteLine("Elapsed TotalSeconds: " + PhRTiming.TsElapsed.TotalSeconds.ToString());
double secsElapsed = sw.Elapsed.TotalSeconds;
// Debug.WriteLine("\ndouble secsElapsed = sw.Elapsed.TotalSeconds; : " + secsElapsed.ToString());
}
catch (Exception) { }
try
{
//Do not think this is doing anything, as secs2 is no value,
Interlocked.Add(ref secs, secs2);
//Debug.WriteLine("\nsecs : " + secs.ToString());
}
catch (Exception){}
mediaElement.MediaEnded -= endOfPlayHandler;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Discovery.Core.Enums
{
/// <summary>
/// 表示搜索的内容类型
/// </summary>
public enum SearchType
{
/// <summary>
/// 搜索用户
/// </summary>
SearchUser,
/// <summary>
/// 搜索帖子
/// </summary>
SearchPost
}
}
|
using System;
using Xamarin.Forms;
namespace Nitro_Smart_Viewer
{
public class ImagePage : ContentPage
{
public ImagePage(object detail)
{
string fileName = "";
string displayName = "";
var resourceFileData = detail as ResourceFileData;
if (resourceFileData != null)
{
fileName = resourceFileData.FileName;
displayName = resourceFileData.DisplayName;
}
Label header = new Label
{
Text = displayName,
FontSize = 20,
FontAttributes = FontAttributes.Bold,
HorizontalOptions = LayoutOptions.Center
};
Image image = new Image
{
// Some differences with loading images in initial release.
Source = Device.OnPlatform(ImageSource.FromResource(fileName), ImageSource.FromResource(fileName), ImageSource.FromResource(fileName)),
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.CenterAndExpand,
HeightRequest = 300
};
Button dismissButton = new Button { Text = "Close", HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.End};
dismissButton.Clicked += OnButtonClicked;
// Build the page.
this.Content = new StackLayout
{
Children =
{
header,
image,
dismissButton
}
};
}
private void OnButtonClicked(object sender, EventArgs e)
{
Navigation.PopModalAsync();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.IO;
public class GameUI : MonoBehaviour
{
public HealthHandler healthbar;
public EnemyHealth healthbar2;
public GameObject pauseScreen;
public GameObject optionScreen;
public ScoreGame score;
void Update()
{
if (healthbar.health <= 0f)
{
YouLose();
return;
}
if (healthbar2.health <= 0f)
{
YouWin();
return;
}
if (Input.GetKeyDown(KeyCode.Escape) && !optionScreen.activeSelf && SongManager.songStarted)
{
if (!SongManager.paused)
{
PauseOnKeyPress();
}
else
{
ResumeOnKeyPress();
}
}
}
public void PauseOnKeyPress()
{
pauseScreen.SetActive(true);
SongManager.paused = true;
}
public void ResumeOnKeyPress()
{
pauseScreen.SetActive(false);
SongManager.paused = false;
}
public void YouWin()
{
FileStream fileStream = File.Open("scoreTemp.data", FileMode.Open); //Flush File
fileStream.SetLength(0);
fileStream.Close();
StreamWriter OurFile = File.CreateText("scoreTemp.data");
OurFile.WriteLine("" + score.TheScore);
OurFile.Close();
SceneManager.LoadScene("WinScreen");
return;
}
public void YouLose()
{
FileStream fileStream = File.Open("scoreTemp.data", FileMode.Open); //Flush File
fileStream.SetLength(0);
fileStream.Close();
StreamWriter OurFile = File.CreateText("scoreTemp.data");
OurFile.WriteLine("" + score.TheScore);
OurFile.Close();
SceneManager.LoadScene("LoseScreen");
return;
}
} |
using System;
using FinanceBot.Views.Update;
namespace FinanceBot.Models.CommandsException
{
public class CategoryAlredyExistException : CommandExeption
{
public CategoryAlredyExistException(string categoryName)
{
base.BadCommand = string
.Format(SimpleTxtResponse.CategoryAlredyExist, categoryName);
}
}
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.PowerShell.EditorServices.Services;
using Microsoft.PowerShell.EditorServices.Services.DebugAdapter;
using Microsoft.PowerShell.EditorServices.Utility;
using OmniSharp.Extensions.DebugAdapter.Protocol.Models;
using OmniSharp.Extensions.DebugAdapter.Protocol.Requests;
namespace Microsoft.PowerShell.EditorServices.Handlers
{
internal class VariablesHandler : IVariablesHandler
{
private readonly ILogger _logger;
private readonly DebugService _debugService;
public VariablesHandler(
ILoggerFactory loggerFactory,
DebugService debugService)
{
_logger = loggerFactory.CreateLogger<ScopesHandler>();
_debugService = debugService;
}
public Task<VariablesResponse> Handle(VariablesArguments request, CancellationToken cancellationToken)
{
VariableDetailsBase[] variables =
_debugService.GetVariables(
(int)request.VariablesReference);
VariablesResponse variablesResponse = null;
try
{
variablesResponse = new VariablesResponse
{
Variables =
variables
.Select(LspDebugUtils.CreateVariable)
.ToArray()
};
}
catch (Exception)
{
// TODO: This shouldn't be so broad
}
return Task.FromResult(variablesResponse);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventConst
{
//< 在关卡界面选择关卡时
public const string EVENT_LEVELSELECT = "OnLevelSelect";
//< 剩余时间更新时
public const string EVENT_UPDATETIMELEFT = "UpdateTimeLeft";
//< 关卡输了
public const string EVENT_GAMELOSE = "GameLose";
//< 关卡通过
public const string EVENT_LEVELPASS = "LevelPass";
//< 当玩家开始捡垃圾时
public const string EVENT_OnStartPickUp = "StartPickUp";
//< 当玩家打断捡垃圾进程时
public const string EVENT_OnBreakPickUp = "BreakPickUp";
//<玩家检索到垃圾时
public const string EVENT_OnLockGarbage = "LockGarbagePos";
//<玩家捡起垃圾时
public const string EVENT_OnPickedUp = "PickedUp";
//<当玩家切换状态时
public const string EVENT_OnToolSwitch = "SwitchTool";
//<当玩家使用清洁工具时
public const string EVENT_OnToolUse = "UseTool";
//<当玩家的垃圾袋清洁度发生变化时
public const string EVENT_OnCapacityChanges = "PackageCapacityChange";
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Main.SimUDuck;
using Main.WeatherStation;
namespace Main
{
class Program
{
static void Main(string[] args)
{
do
{
//// ======================Strategy Pattern==========================
//Console.WriteLine(Constant.Exit);
//Duck donal = new DonalDuck();
//donal.performFly();
//donal.performQuack();
//donal.display();
//Console.WriteLine(Environment.NewLine);
//Duck model = new ModelDuck();
//model.display();
//model.performFly();
//model.setFlyBehavior(new FlyRocketPowered());
//model.performFly();
//model.performQuack();
//model.performSwim();
//========================Observer Pattern============================
WeatherData weatherData = new WeatherData();
WeatherData forecastWeatherData = new WeatherData();
CurrentConditionDisplay currentDisplay = new CurrentConditionDisplay(weatherData);
ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);
weatherData.setMeasurements(55, 0.85, 1.22);
weatherData.setMeasurements(75, 0.55, 1.05);
weatherData.setMeasurements(85, 0.45, 0.85);
//Console.WriteLine("Forecast for tomorrow: ");
//forecastWeatherData.setMeasurements(35, 0.85, 1.22);
//forecastWeatherData.setMeasurements(25, 0.55, 1.05);
//forecastWeatherData.setMeasurements(15, 0.45, 0.85);
}
while (Console.ReadKey().Key != ConsoleKey.NumPad0);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
namespace GameStore.WebUI.Apis
{
public class AccountController : BaseApiController
{
/*
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async HttpResponseMessage Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new AppUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var newUser = UserManager.FindByEmail(model.Email);
var identity = await UserManager.CreateIdentityAsync(newUser, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, GetErrorMessage(result));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}*/
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestScript : MonoBehaviour {
private void OnBecameInvisible()
{
Debug.Log("You are Out");
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using JsonBAM.Data;
using JsonBAM.Data.Entities;
using Newtonsoft.Json;
namespace JsonBAM.Controllers
{
public class HitMeController : Controller
{
[HttpPost]
[AllowAnonymous]
public ActionResult Index(string key)
{
var json = new StreamReader(Request.InputStream).ReadToEnd();
var headers = JsonConvert.SerializeObject(Request.Headers.AllKeys.Select(x => new {
Name = x,
Value = Request.Headers.Get(x)
}));
using (var db = new BamEntities())
{
var log = new Log()
{
Key = key,
DateCreated = DateTime.Now,
LogJson = json,
HeaderJson = headers,
Verb = Request.HttpMethod
};
db.Logs.Add(log);
db.SaveChanges();
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
} |
namespace SharpDL.Graphics
{
public interface IWindowFactory
{
/// <summary>Creates a Window used for display and rendering.
/// </summary>
/// <param name="title">String displayed in the Window title bar.</param>
/// <returns>Instance of a Window.</returns>
IWindow CreateWindow(string title);
/// <summary>Creates a Window used for display and rendering.
/// </summary>
/// <param name="title">String displayed in the Window title bar.</param>
/// <param name="x">X coordinate to position the Window.</param>
/// <param name="y">Y coordinate to position the Window.</param>
/// <returns>Instance of a Window.</returns>
IWindow CreateWindow(string title, int x, int y);
/// <summary>Creates a Window used for display and rendering.
/// </summary>
/// <param name="title">String displayed in the Window title bar.</param>
/// <param name="x">X coordinate to position the Window.</param>
/// <param name="y">Y coordinate to position the Window.</param>
/// <param name="width">Width of the Window.</param>
/// <param name="height">Height of the Window.</param>
/// <returns>Instance of a Window.</returns>
IWindow CreateWindow(string title, int x, int y, int width, int height);
/// <summary>Creates a Window used for display and rendering.
/// </summary>
/// <param name="title">String displayed in the Window title bar.</param>
/// <param name="x">X coordinate to position the Window.</param>
/// <param name="y">Y coordinate to position the Window.</param>
/// <param name="width">Width of the Window.</param>
/// <param name="height">Height of the Window.</param>
/// <param name="flags">Flags to give special behaviors and features to the Window.</param>
/// <returns>Instance of a Window.</returns>
IWindow CreateWindow(string title, int x, int y, int width, int height, WindowFlags flags);
}
} |
using System;
namespace Emanate.Core
{
public interface IModuleType
{
Type ModuleType { get; }
}
} |
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using DavisVantage.WeatherReader.Logging;
using DavisVantage.WeatherReader.Models;
using DavisVantage.WeatherReader.Models.Extremes;
namespace DavisVantage.WeatherReader.WeatherLinkIp
{
public class WeatherLinkIpDataLogger : IDataLogger<WeatherLinkIpSettings>
{
public WeatherLinkIpSettings Settings { get; set; }
private readonly IByteReader _byteReader;
private TcpClient _tcpClient;
private static readonly ILog s_logger = LogProvider.For<WeatherLinkIpDataLogger>();
public WeatherLinkIpDataLogger(IByteReader byteReader, IDataLoggerSettings settings)
{
_byteReader = byteReader;
Settings = settings as WeatherLinkIpSettings;
}
public bool Connect()
{
try
{
if (Settings == null)
{
s_logger.Warn("No connection could be established. Settings are empty.");
return false;
}
_tcpClient = new TcpClient();
// wait for connection
if (!_tcpClient.ConnectAsync(Settings.IpAddress, Settings.Port).Wait(TimeSpan.FromSeconds(5)))
{
s_logger.Error($"Could not connect to {Settings?.IpAddress}:{Settings?.Port}");
return false;
}
return _tcpClient.Connected;
}
catch (Exception)
{
s_logger.Error($"Could not connect to {Settings?.IpAddress}:{Settings?.Port}");
return false;
}
}
public async Task<CurrentWeather> ReadCurrentWeather(bool valuesInMetric)
{
try
{
if (WakeUp())
{
const string COMMAND = "LOOP 1\n";
var commandInBytes = Encoding.ASCII.GetBytes(COMMAND);
var networkStream = _tcpClient.GetStream();
networkStream.ReadTimeout = 10000;
networkStream.Write(commandInBytes, 0, commandInBytes.Length);
if (networkStream.DataAvailable)
{
ReadUntilAckByte(networkStream);
var dataBuffer = new byte[99];
networkStream.Read(dataBuffer, 0, dataBuffer.Length);
return await _byteReader.ReadCurrentWeatherFromByteArray(dataBuffer, valuesInMetric);
}
s_logger.Warn("Could not read current weather data. No data available");
}
return null;
}
catch (Exception ex)
{
s_logger.ErrorException("Could not read current weather data. ", ex);
return null;
}
}
public async Task<WeatherExtremes> ReadWeatherExtremes(bool valuesInMetric)
{
try
{
if (WakeUp())
{
const string COMMAND = "HILOWS\n";
var commandInBytes = Encoding.ASCII.GetBytes(COMMAND);
var networkStream = _tcpClient.GetStream();
networkStream.Write(commandInBytes, 0, commandInBytes.Length);
if (networkStream.DataAvailable)
{
ReadUntilAckByte(networkStream);
var dataBuffer = new byte[438];
networkStream.Read(dataBuffer, 0, dataBuffer.Length);
return await _byteReader.ReadWeatherExtremesFromByteArray(dataBuffer, valuesInMetric);
}
s_logger.Warn("Could not read weather extremes. No data available");
}
return null;
}
catch (Exception ex)
{
s_logger.ErrorException("Could not read weather extremes.", ex);
return null;
}
}
public void Dispose()
{
if (_tcpClient?.Connected ?? false)
{
#if NET451
_tcpClient.Close();
#else
_tcpClient.Dispose();
#endif
}
}
private bool WakeUp()
{
try
{
const byte NEWLINECHAR = 10;
var networkStream = _tcpClient.GetStream();
var dataAvailable = RetryPolicies.WakeUpPolicy.Execute(() =>
{
s_logger.Info("Trying to wake up the console");
networkStream.WriteByte(NEWLINECHAR);
return networkStream.DataAvailable;
});
if (dataAvailable)
{
s_logger.Info("Console has been woken up succesfully!");
return true;
}
else
{
s_logger.Warn("Could not initiate wake up call. Response from Console was empty.");
return false;
}
}
catch (Exception ex)
{
s_logger.ErrorException("Could not initiate wake up call. ", ex);
return false;
}
}
private void ReadUntilAckByte(NetworkStream networkStream)
{
const int ACK = 6;
var ackFound = false;
while (!ackFound)
{
var value = networkStream.ReadByte();
if (value == -1)
{
throw new Exception("Empty response from console");
}
ackFound = (value == ACK);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity;
namespace angserver.Classes
{
public class IdentityUser : IUser<string>
{
public string Name { get; set; }
public string Id { get; private set; }
public string UserName { get; set; }
}
} |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace TheMinepack.Projectiles
{
public class StarScytheProjectile2 : ModProjectile
{
public override void SetDefaults()
{
projectile.CloneDefaults(ProjectileID.Starfury);
projectile.name = "Small Star";
projectile.width = 22;
projectile.height = 22;
projectile.aiStyle = 5;
aiType = 9;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineTabletop.Models
{
public interface IRepository<T>: ICollection<T>
where T:IEntity
{
T Get(string id);
}
}
|
using AutoDataReader.Entities.Base;
using System;
using System.Collections.Generic;
using System.Text;
namespace AutoDataReader.Entities
{
class WordDto : Word
{
public List<Link> Links { get; set; } = new List<Link>();
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amesc.Dominio;
using Amesc.Dominio.Cursos;
using Amesc.Dominio._Consultas;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Amesc.WebApp.Controllers
{
public class RelatorioAnaliticoPorCursoController : Controller
{
private readonly IDadosAnaliticosPorCursoConsulta _dadosAnaliticosPorCursoConsulta;
private readonly IRepositorio<Curso> _cursoRepositorio;
public RelatorioAnaliticoPorCursoController(
IDadosAnaliticosPorCursoConsulta dadosAnaliticosPorCursoConsulta,
IRepositorio<Curso> cursoRepositorio)
{
_dadosAnaliticosPorCursoConsulta = dadosAnaliticosPorCursoConsulta;
_cursoRepositorio = cursoRepositorio;
}
public async Task<IActionResult> Index(int? cursoId, int? ano)
{
var cursos = _cursoRepositorio.Consultar();
ViewBag.Cursos = cursos.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = $"{c.Nome}",
Selected = cursoId.HasValue && c.Id == cursoId.Value
}).ToList();
ViewBag.Anos = new List<int> { 2017, 2018, 2019, 2020 }.Select(c => new SelectListItem
{
Value = c.ToString(),
Text = c.ToString(),
Selected = ano == c
}).ToList();
if (!cursoId.HasValue)
return View(null);
var consulta = await _dadosAnaliticosPorCursoConsulta.Consultar(cursoId.Value, ano.Value);
return View(consulta);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Studentum.Infrastructure.Repository;
namespace BreakAway.Domain
{
[Repository(AggregateName = "BreakAway")]
public class ActivityRepository : RepositoryBase<Activity>, IRepository<Activity>
{
public ActivityRepository(IRepositoryProviderBase repositoryProvider) : base(repositoryProvider) { }
}
}
|
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Android;
namespace MvxForms.Starter.UITests.Android
{
[TestFixture]
public class Tests
{
AndroidApp app;
[SetUp]
public void BeforeEachTest()
{
app = ConfigureApp
.Android
.ApkFile(@"..\..\..\MvxForms.Starter.App\MvxForms.Starter.App.Android\bin\Release\com.MvxForms.Starter.App.apk")
.EnableLocalScreenshots()
.StartApp();
}
[Test]
public void AppLaunches()
{
app.Screenshot("First screen.");
}
[Test]
public void AppNavigateSecondView()
{
app.WaitForElement(c => c.Marked("BtnNext").Text("Go next"));
app.Tap(c => c.Marked("BtnNext"));
app.WaitForElement(c => c.Marked("LblTitle"));
app.Screenshot("Second screen.");
}
[Test]
public void AppNavigateBack()
{
app.WaitForElement(c => c.Marked("BtnNext").Text("Go next"));
app.Tap(c => c.Marked("BtnNext"));
app.WaitForElement(c => c.Marked("LblTitle"));
app.Tap(c => c.Marked("BtnBack"));
app.WaitForElement(c => c.Marked("BtnNext").Text("Go next"));
app.WaitForElement(c => c.Marked("EntryText").Text("Hello MvvmCross !BackParam"));
app.Screenshot("First screen back");
}
[Test]
public void AppResetBtn()
{
app.WaitForElement(c => c.Marked("EntryText").Text("Hello MvvmCross !"));
app.Tap(c => c.Marked("BtnReset"));
app.WaitForElement(c => c.Marked("EntryText").Text("Hello MvvmCross"));
app.Screenshot("First screen reset");
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
namespace Calcifer.Engine.Content.Data
{
public class ProviderCollection
{
private readonly DirectoryNode root;
public ProviderCollection()
{
root = new DirectoryNode(null, "");
}
public void Add(IContentProvider provider)
{
var separator = new[]{'\\', '/'};
foreach (AssetEntry current in provider.GetAssets())
{
string[] array = current.FullName.Split(separator, StringSplitOptions.RemoveEmptyEntries);
DirectoryNode directory = root;
for (int i = 0; i < array.Length - 1; i++)
{
if (!directory.HasDirectory(array[i]))
{
directory.Add(array[i]);
}
directory = directory.GetDirectory(array[i]);
}
if (directory.Files.ContainsKey(current.Name))
{
directory.Files[current.Name] = current;
}
else
{
directory.Files.Add(current.Name, current);
}
}
}
public Stream LoadAsset(string assetName)
{
var separator = new[] { '\\', '/' };
string[] array = assetName.Split(separator, StringSplitOptions.RemoveEmptyEntries);
DirectoryNode directory = root;
string key = array[array.Length - 1];
for (int i = 0; i < array.Length - 1; i++)
{
if (!directory.HasDirectory(array[i]))
{
throw new DirectoryNotFoundException(string.Format("Directory not found: {0}", array[i]));
}
directory = directory.GetDirectory(array[i]);
}
if (!directory.Files.ContainsKey(key))
{
throw new FileNotFoundException(string.Format("File not found: {0}", assetName));
}
return directory.Files[key].Load();
}
private sealed class DirectoryNode
{
private readonly Dictionary<string, DirectoryNode> children;
private readonly DirectoryNode parent;
public DirectoryNode(DirectoryNode parent, string name)
{
this.parent = parent;
Name = name;
Files = new Dictionary<string, AssetEntry>();
children = new Dictionary<string, DirectoryNode>();
}
public string Name { get; set; }
public Dictionary<string, AssetEntry> Files { get; private set; }
public string FullName
{
get
{
if (parent == null)
{
return "";
}
return (parent.parent != null) ? (parent.FullName + "/" + Name) : Name;
}
}
public void Add(string directory)
{
children.Add(directory, new DirectoryNode(this, directory));
}
public DirectoryNode GetDirectory(string directory)
{
return children[directory];
}
public bool HasDirectory(string directory)
{
return children.ContainsKey(directory);
}
}
}
} |
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using JsonFx.Json;
using UnityEngine;
/// <summary>
/// Extended functionality wrapper for Unity's Input class.
/// Handles controllers in different platforms in a unified fashion.
/// It is preferred to use this class instead of UnityEngine.Input.
///
///
/// </summary>
/// <description>
/// Requires all joystick axes up to 8 configured in Input Manager
/// with names Joy[x], where x is the name of the axis configured.
///
/// Keys and axis names for XBox controllers:
/// Keys:
/// :a, :b, :x, :y, :right trigger, :left trigger, left bumper,
/// right bumper, up arrow, down arrow, right arrow, left arrow, back, start
/// Axes:
/// left stick x, left stick y, right stick x, right stick y,
/// bumper axis, vertical arrow axis, horizontal arrow axis
/// </description>
/// <remarks>
/// Platform controller reference cheatsheets (Win, Mac, Linux) in that order:
/// http://wiki.unity3d.com/index.php?title=Xbox360Controller
/// </remarks>
public class JoyInput {
/// <summary>
/// The controller axis dispatch table.
/// Keys are axis names, funcs return the value of that axis
/// </summary>
private static Dictionary<string, Func<float>> joyAxisDispatch;
/// <summary>
/// The controller button dispatch table.
/// Keys are button names, funcs return their state.
/// </summary>
private static Dictionary<string, Func<bool>> joyButtonDispatch;
/// <summary>
/// The key mapping. Initialized from file at first access to this class,
/// individual keymaps can be accessed with <see cref="GetMappingFor"/>,
/// and redefined with <see cref="Remap()"/>.
/// </summary>
private static Dictionary<string, string> keyMapping;
/// <summary>
/// Returns the current key mapping for the given input name.
/// </summary>
/// <returns>The internal axis or key defined for this name</returns>
/// <param name="axisOrKeyName">Axis or key name to retrieve.</param>
public static string GetMappingFor(string axisOrKeyName) {
TryInitialize();
try {
return keyMapping[axisOrKeyName.ToLower()].ToLower();
} catch {
Debug.Log(axisOrKeyName);
return "";
}
}
/// <summary>
/// Gets the current value of the given axis.
/// </summary>
/// <returns>The axis value, usually between -1 and 1.</returns>
/// <param name="axisName">Pretty axis name.</param>
public static float GetAxis(string axisName) {
return GetAxisRaw(GetMappingFor(axisName));
}
/// <summary>
/// Gets the button state.
/// </summary>
/// <returns><c>true</c>, if button is down, <c>false</c> otherwise.</returns>
/// <param name="name">Pretty name of the button.</param>
public static bool GetButton(string name) {
return GetButtonRaw(GetMappingFor(name));
}
/// <summary>
/// Similar to <see cref="GetAxis"/>, but bypasses the keymap table
/// </summary>
/// <returns>The axis' raw value.</returns>
/// <param name="axisName">Axis name.</param>
public static float GetAxisRaw(string axisName) {
TryInitialize();
var keys = SplitKeymap(axisName);
var sum = keys.Aggregate(0f, (accumulator, axis) => {
if (joyAxisDispatch.ContainsKey(axis)) {
accumulator += joyAxisDispatch[axis]();
} else {
accumulator += Input.GetAxis(axis);
}
return accumulator;
});
return Mathf.Clamp(sum, -1f, 1f);
}
/// <summary>
/// Similar to <see cref="GetButton"/>, but bypasses the keymap table
/// </summary>
/// <returns><c>true</c>, if button button is down, <c>false</c> otherwise.</returns>
/// <param name="name">Button name.</param>
public static bool GetButtonRaw(string name) {
TryInitialize();
var keys = SplitKeymap(name);
return keys.Any(key => {
if (joyButtonDispatch.ContainsKey(key)) {
return joyButtonDispatch[key]();
}
return Input.GetKey(key);
});
}
/// <summary>
/// Remap the specified "pretty name" to the target key or axis.
/// </summary>
/// <param name="name">Pretty/descriptive name.</param>
/// <param name="target">Target key or axis.</param>
public static void Remap(string name, string target) {
TryInitialize();
keyMapping[name.ToLower()] = target.ToLower();
}
/// <summary>
/// Tries to initialize the class. All public functions should call this
/// function before accessing any functionality.
///
/// Defines dispatch tables for axis and buttons, and loads the keymap file
/// </summary>
private static void TryInitialize() {
if (keyMapping == null) {
LoadKeymap();
}
if (joyAxisDispatch == null) {
joyAxisDispatch = new Dictionary<string, Func<float>>();
joyAxisDispatch.Add("left stick x", () => {
return Input.GetAxis("JoyX");
});
joyAxisDispatch.Add("left stick y", () => {
return Input.GetAxis("JoyY");
});
joyAxisDispatch.Add("right stick x", () => {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX
return Input.GetAxis("Joy4");
#elif UNITY_STANDALONE_OSX
return Input.GetAxis("Joy3");
#endif
});
joyAxisDispatch.Add("right stick y", () => {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX
return Input.GetAxis("Joy5");
#elif UNITY_STANDALONE_OSX
return Input.GetAxis("Joy4");
#endif
});
joyAxisDispatch.Add("bumper axis", () => {
return (JoyInput.GetButtonRaw("right bumper")?1:0)
+ (JoyInput.GetButtonRaw("left bumper")?-1:0);
});
joyAxisDispatch.Add("vertical arrow axis", () => {
return (JoyInput.GetButtonRaw("up arrow")?1:0)
+ (JoyInput.GetButtonRaw("down arrow")?-1:0);
});
joyAxisDispatch.Add("horizontal arrow axis", () => {
return (JoyInput.GetButtonRaw("right arrow")?1:0)
+ (JoyInput.GetButtonRaw("left arrow")?-1:0);
});
}
if (joyButtonDispatch == null) {
joyButtonDispatch = new Dictionary<string, Func<bool>>();
joyButtonDispatch.Add (":a", () => {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX
return Input.GetKey("joystick button 0");
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 16");
#endif
});
joyButtonDispatch.Add (":b", () => {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX
return Input.GetKey("joystick button 1");
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 17");
#endif
});
joyButtonDispatch.Add (":x", () => {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX
return Input.GetKey("joystick button 2");
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 18");
#endif
});
joyButtonDispatch.Add (":y", () => {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX
return Input.GetKey("joystick button 3");
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 19");
#endif
});
joyButtonDispatch.Add(":right trigger", () => {
#if UNITY_STANDALONE_WIN
return Input.GetAxis("Joy3") < 0f;
#elif UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX
return Input.GetAxis("Joy6") > 0f;
#endif
});
joyButtonDispatch.Add(":left trigger", () => {
#if UNITY_STANDALONE_WIN
return Input.GetAxis("Joy3") > 0f;
#elif UNITY_STANDALONE_LINUX
return Input.GetAxis("Joy3") > 0f;
#elif UNITY_STANDALONE_OSX
return Input.GetAxis("Joy5") > 0f;
#endif
});
joyButtonDispatch.Add("left bumper", () => {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX
return Input.GetKey("joystick button 4");
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 13");
#endif
});
joyButtonDispatch.Add("right bumper", () => {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX
return Input.GetKey("joystick button 5");
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 14");
#endif
});
joyButtonDispatch.Add("up arrow", () => {
#if UNITY_STANDALONE_WIN
return Input.GetAxis("Joy7") > 0;
#elif UNITY_STANDALONE_LINUX
return Input.GetAxis("Joy8") > 0;
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 5");
#endif
});
joyButtonDispatch.Add("down arrow", () => {
#if UNITY_STANDALONE_WIN
return Input.GetAxis("Joy7") < 0;
#elif UNITY_STANDALONE_LINUX
return Input.GetAxis("Joy8") < 0;
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 6");
#endif
});
joyButtonDispatch.Add("right arrow", () => {
#if UNITY_STANDALONE_WIN
return Input.GetAxis("Joy6") > 0;
#elif UNITY_STANDALONE_LINUX
return Input.GetAxis("Joy7") > 0;
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 7");
#endif
});
joyButtonDispatch.Add("left arrow", () => {
#if UNITY_STANDALONE_WIN
return Input.GetAxis("Joy6") < 0;
#elif UNITY_STANDALONE_LINUX
return Input.GetAxis("Joy7") < 0;
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 8");
#endif
});
joyButtonDispatch.Add("back", () => {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX
return Input.GetKey("joystick button 6");
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 10");
#endif
});
joyButtonDispatch.Add("start", () => {
#if UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX
return Input.GetKey("joystick button 7");
#elif UNITY_STANDALONE_OSX
return Input.GetKey("joystick button 9");
#endif
});
}
}
/// <summary>
/// Loads the keymapping file, keymap.json, which should be located on the Assets folder.
/// </summary>
private static void LoadKeymap() {
using (var file = new StreamReader(Path.Combine(Application.dataPath, "keymap.json"))) {
var reader = new JsonReader(file);
keyMapping = reader.Deserialize<Dictionary<string, string>>();
}
}
/// <summary>
/// Splits a keymap definition into multiple keys.
/// </summary>
/// <returns>The keymap rule</returns>
/// <param name="keymap">Equivalent keys.</param>
private static IEnumerable<string> SplitKeymap(string keymap) {
return new List<string>(keymap.Split('|')).Select(str => str.Trim());
}
}
|
using Common;
using DeferredRender.Graphics;
using OpenTK;
namespace DeferredRender
{
public static class Extensions
{
public static void Bind(this SimpleModel model, Matrix4 modelView, Matrix4 modelViewProjection, Matrix4 projection)
{
if (model.TextureId == -1)
{
Shaders.BindTexturelessNoLight(model, modelView, modelViewProjection, projection);
}
else
{
Shaders.BindTexturedNoLight(model, modelView, modelViewProjection, projection);
}
}
}
}
|
using AuditAppPcl.Manager.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AuditAppPcl.Entities;
using AuditAppPcl.Repository.Contracts;
namespace AuditAppPcl.Manager.Concrete
{
public class CaseServiceManager : ICaseServiceManager
{
private readonly ICaseServiceRepository caseServiceRepository;
public CaseServiceManager(ICaseServiceRepository caseServiceRepository)
{
this.caseServiceRepository = caseServiceRepository;
}
public List<Case> GetCases()
{
var data = Task.Run(async () => await caseServiceRepository.GetCases()).Result;
if(data != null && data.Success)
{
return data.Cases;
}
return null;
}
public List<Case> GetCasesWithAudits()
{
var data = Task.Run(async () => await caseServiceRepository.GetCasesWithAudits()).Result;
if (data != null && data.Success)
{
return data.Cases;
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Application.Common.Dtos;
using Application.Common.Exceptions;
using Application.Common.Interface;
using Application.Common.Models;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Application.Client.Queries {
public class SearchByCategoryQueries : IRequest<List<ProductsDto>> {
public string CategoryName { get; set; }
}
public class SearchByCategoryQueriesHandler : BaseCommandHandler<SearchByCategoryQueriesHandler>, IRequestHandler<SearchByCategoryQueries, List<ProductsDto>> {
public SearchByCategoryQueriesHandler (IAppDbContext context, IMapper mapper, ILogger<SearchByCategoryQueriesHandler> logger) : base (context, mapper, logger) { }
public async Task<List<ProductsDto>> Handle (SearchByCategoryQueries request, CancellationToken cancellationToken) {
var entity = await Context.Products.Where (x => x.CategoryName == request.CategoryName).ProjectTo<ProductsDto> (Mapper.ConfigurationProvider).ToListAsync (cancellationToken);
if (entity == null) throw new NotFoundException ("Product", "Not found!");
return entity;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AplicativoDeChamada
{
class Disciplina
{
public string disciplina;
public string disciplinaAsString()
{
return disciplina;
}
public void disciplinaFromString(string data)
{
string[] info = data.Split('#');
disciplina = info[0];
}
}
}
|
using Shunxi.Business.Models.devices;
namespace Shunxi.Business.Models
{
public class Consumable :ViewModel
{
public int _id;
public int Id
{
get => _id;
set
{
_id = value;
OnPropertyChanged();
}
}
public string _name;
public string Name
{
get => _name;
set
{
_name = value;
OnPropertyChanged();
}
}
public string _origin;
public string Origin
{
get => _origin;
set
{
_origin = value;
OnPropertyChanged();
}
}
public string _ConsumableSerialNumber;
public string ConsumableSerialNumber
{
get => _ConsumableSerialNumber;
set
{
_ConsumableSerialNumber = value;
OnPropertyChanged();
}
}
private string _ConsumableName;
public string ConsumableName
{
get => _ConsumableName;
set
{
_ConsumableName = value;
OnPropertyChanged();
}
}
public int _ConsumableUsedTimes;
public int ConsumableUsedTimes
{
get => _ConsumableUsedTimes;
set
{
_ConsumableUsedTimes = value;
OnPropertyChanged();
}
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Codewars.MultiplesOf3or5.Tests
{
[TestClass]
public class KataTests
{
[TestMethod]
public void Test()
{
Assert.AreEqual(23, Kata.Solution(10));
Assert.AreEqual(258, Kata.Solution(34));
Assert.AreEqual(0, Kata.Solution(-34));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls.Expressions;
namespace treatment.Models
{
public class Voter
{
public int VoterID { get; set; }
public string VoterNumber { set; get; }
public string Name { set; get; }
public string Address { get; set; }
public string DateOFBirth { set; get; }
}
} |
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace nargileotomasyon.Models.Mapping
{
public class markaMap : EntityTypeConfiguration<marka>
{
public markaMap()
{
// Primary Key
this.HasKey(t => t.markid);
// Properties
this.Property(t => t.markadı)
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("marka");
this.Property(t => t.markid).HasColumnName("markid");
this.Property(t => t.ürünid).HasColumnName("ürünid");
this.Property(t => t.markadı).HasColumnName("markadı");
}
}
}
|
//Problem 11. Bitwise: Extract Bit #3
// Using bitwise operators, write an expression for finding the value of the bit #3 of a given unsigned integer.
// The bits are counted from right to left, starting from bit #0 .
// The result of the expression should be either 1 or 0 .
using System;
namespace Problem11BitwiseExtractBitThree
{
class BitwiseExtractBitThree
{
static void Main()
{
UInt32 data;
try
{
Console.Write("Enter integer number: ");
data = UInt32.Parse(Console.ReadLine());
Console.WriteLine("Third bit is {0}", ((data >> 3) & 1));
}
catch
{
// Wrong format is entered. Handle exception
Console.WriteLine("Format of entered data is not correct");
}
}
}
} |
using JumpAndRun.Networking;
using System.Net.Sockets;
using GameLib.Networking;
namespace JumpAndRun.ServerRuntime
{
internal class Client
{
public JumpAndRunStream Stream;
public TcpClient TcpClient;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Enrollment.Forms.Parameters.Common
{
public enum DetailItemEnum
{
Field,
Group,
List
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class q3 : Form
{
const int AW_SLIDE = 0X40000;
const int AW_HOR_POSITIVE = 0X1;
const int AW_HOR_NEGATIVE = 0X2;
const int AW_BLEND = 0X80000;
[DllImport("user32")]
static extern bool AnimateWindow(IntPtr hwnd, int time, int flags);
public q3()
{
InitializeComponent();
Resize += Form1_Resize;
this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true);
}
private void Form1_Resize(object sender, System.EventArgs e)
{
this.Update();
}
private void q3Click(object sender, EventArgs e)
{
PictureBox imgObj = sender as PictureBox;
if (Convert.ToInt16(imgObj.Tag) == 1)
{
Form1.qanswers.Add(1);
//this.Close();
}
else if (Convert.ToInt16(imgObj.Tag) == 2)
{
Form1.qanswers.Add(2);
}
else if (Convert.ToInt16(imgObj.Tag) == 3)
{
Form1.qanswers.Add(3);
}
//if (imgObj.Tag == pictureBox1.Tag)
//{
// Form1.qanswers.Add(1);
// //this.Close();
//}
//else if (imgObj.Tag == pictureBox2.Tag)
//{
// Form1.qanswers.Add(2);
//}
//else
//{
// Form1.qanswers.Add(3);
//}
q4 q4Obj = new q4();
q4Obj.Show();
this.Close();
}
protected override void OnLoad(EventArgs e)
{
//Load the Form At Position of Main Form
int WidthOfMain = Application.OpenForms["LoginForm"].Width;
int HeightofMain = Application.OpenForms["LoginForm"].Height;
int LocationMainX = Application.OpenForms["LoginForm"].Location.X;
int locationMainy = Application.OpenForms["LoginForm"].Location.Y;
//Set the Location
this.Location = new Point(LocationMainX + WidthOfMain, locationMainy + 10);
//Animate form
AnimateWindow(this.Handle, 500, AW_SLIDE | AW_HOR_POSITIVE);
}
private void q3_Load(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using UnityEngine;
using System.Collections;
public class commandPointMove : MonoBehaviour {
public GameObject followTarget;
private NavMeshAgent navAgent;
// Use this for initialization
void Start () {
navAgent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update () {
navAgent.destination = followTarget.transform.position;
}
}
|
using System;
using System.Threading;
namespace progr12
{
class Program
{
static void Main()
{
Console.Title = "Информация о главном потоке программы";
Thread thread = Thread.CurrentThread;
thread.Name = "MyThread";
Console.WriteLine(@"Имя домена приложения: {0}
ID контекста: {1}
Имя потока: {2}
Запущен ли поток? {3}
Приоритет потока: {4}
Состояние потока: {5}",
Thread.GetDomain().FriendlyName, Thread.CurrentThread.ManagedThreadId, thread.Name, thread.IsAlive, thread.Priority, thread.ThreadState);
Console.ReadLine();
}
}
}
|
namespace Triton.Game.Abstraction
{
using ns27;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Triton.Game.Mapping;
public class Entity : Triton.Game.Abstraction.EntityBase
{
[CompilerGenerated]
private Triton.Game.Mapping.Entity entity_0;
[CompilerGenerated]
private Triton.Game.Abstraction.EntityDef entityDef_0;
[CompilerGenerated]
private int int_24;
[CompilerGenerated]
private int int_25;
[CompilerGenerated]
private int int_26;
[CompilerGenerated]
private int int_27;
[CompilerGenerated]
private int int_28;
[CompilerGenerated]
private List<Triton.Game.Abstraction.Entity> list_0;
[CompilerGenerated]
private string string_0;
[CompilerGenerated]
private string string_1;
[CompilerGenerated]
private TAG_CLASS tag_CLASS_0;
[CompilerGenerated]
private TAG_RACE tag_RACE_0;
internal Entity(Triton.Game.Mapping.Entity backingObject) : base(backingObject)
{
this.Entity_0 = backingObject;
this.EntityDef = Class274.Class274_0.method_3(this.Entity_0.GetEntityDef());
this.Name = this.Entity_0.GetName();
this.Id = this.Entity_0.GetCardId();
this.Class = this.Entity_0.GetClass();
this.Race = this.Entity_0.GetRace();
this.RealTimeCost = this.Entity_0.GetRealTimeCost();
this.RealTimeRemainingHP = this.Entity_0.GetRealTimeRemainingHP();
this.RealTimeAttack = this.Entity_0.GetRealTimeAttack();
this.RealTimeArmor = this.Entity_0.m_realTimeArmor;
this.RealTimeDamage = this.Entity_0.m_realTimeDamage;
this.Attachments = new List<Triton.Game.Abstraction.Entity>();
foreach (Triton.Game.Mapping.Entity entity in this.Entity_0.GetAttachments())
{
this.Attachments.Add(Class274.Class274_0.method_2(entity));
}
}
public List<Triton.Game.Abstraction.Entity> Attachments
{
[CompilerGenerated]
get
{
return this.list_0;
}
[CompilerGenerated]
private set
{
this.list_0 = value;
}
}
public TAG_CLASS Class
{
[CompilerGenerated]
get
{
return this.tag_CLASS_0;
}
[CompilerGenerated]
private set
{
this.tag_CLASS_0 = value;
}
}
internal Triton.Game.Mapping.Entity Entity_0
{
[CompilerGenerated]
get
{
return this.entity_0;
}
[CompilerGenerated]
set
{
this.entity_0 = value;
}
}
public Triton.Game.Abstraction.EntityDef EntityDef
{
[CompilerGenerated]
get
{
return this.entityDef_0;
}
[CompilerGenerated]
private set
{
this.entityDef_0 = value;
}
}
public string Id
{
[CompilerGenerated]
get
{
return this.string_1;
}
[CompilerGenerated]
private set
{
this.string_1 = value;
}
}
public string Name
{
[CompilerGenerated]
get
{
return this.string_0;
}
[CompilerGenerated]
private set
{
this.string_0 = value;
}
}
public TAG_RACE Race
{
[CompilerGenerated]
get
{
return this.tag_RACE_0;
}
[CompilerGenerated]
private set
{
this.tag_RACE_0 = value;
}
}
public int RealTimeArmor
{
[CompilerGenerated]
get
{
return this.int_27;
}
[CompilerGenerated]
private set
{
this.int_27 = value;
}
}
public int RealTimeAttack
{
[CompilerGenerated]
get
{
return this.int_26;
}
[CompilerGenerated]
private set
{
this.int_26 = value;
}
}
public int RealTimeCost
{
[CompilerGenerated]
get
{
return this.int_24;
}
[CompilerGenerated]
private set
{
this.int_24 = value;
}
}
public int RealTimeDamage
{
[CompilerGenerated]
get
{
return this.int_28;
}
[CompilerGenerated]
private set
{
this.int_28 = value;
}
}
public int RealTimeRemainingHP
{
[CompilerGenerated]
get
{
return this.int_25;
}
[CompilerGenerated]
private set
{
this.int_25 = value;
}
}
}
}
|
using System.Web.Mvc;
namespace API.ControleRapido.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "API Controle Rápido";
return View();
}
}
}
|
using Swiddler.Utils;
using System;
using System.ComponentModel;
using System.Globalization;
namespace Swiddler.ViewModels
{
public class QuickActionItem
{
public string Icon { get; set; }
public string Caption { get; set; }
public string Description { get; set; }
public QuickActionTemplate Template { get; set; }
protected Action<ConnectionSettings> Builder { get; set; }
public static QuickActionItem[] DefaultTemplates { get; } = new[]
{
new QuickActionItem(QuickActionTemplate.ClientTCPv4),
new QuickActionItem(QuickActionTemplate.ServerTCPv4),
new QuickActionItem(QuickActionTemplate.TunnelTCPv4),
new QuickActionItem(QuickActionTemplate.Sniffer),
//new QuickActionItem(QuickActionTemplate.Monitor),
};
public QuickActionItem(QuickActionTemplate template)
{
Template = template;
switch (template)
{
case QuickActionTemplate.ClientTCPv4:
Icon = "Connect";
Description = "Client (connect to host)";
Builder = cs => { cs.TCPChecked = true; cs.ClientChecked = true; };
break;
case QuickActionTemplate.ServerTCPv4:
Icon = "Port";
Description = "Server (open local port)";
Builder = cs => { cs.TCPChecked = true; cs.ServerChecked = true; };
break;
case QuickActionTemplate.TunnelTCPv4:
Icon = "Tunnel";
Description = "Tunnel (client & server)";
Builder = cs => { cs.TCPChecked = true; cs.ClientChecked = true; cs.ServerChecked = true; };
break;
case QuickActionTemplate.Sniffer:
Icon = "Eye";
Description = "Network sniffer";
Builder = cs =>
{
cs.SnifferChecked = true;
cs.Sniffer.CaptureFilter.Add(new SocketSettings.SnifferSettings.CaptureFilterItem() { Port = 80, Protocol = SocketSettings.SnifferSettings.CaptureProtocol.TCP });
};
break;
case QuickActionTemplate.Monitor:
Icon = "Process";
Description = "Process traffic monitor";
Builder = cs => {}; // TODO
break;
}
}
public virtual bool MatchSearch(string textToFind)
{
if (string.IsNullOrEmpty(textToFind) || string.IsNullOrEmpty(Description)) return true;
return Description.IndexOf(textToFind, StringComparison.OrdinalIgnoreCase) >= 0;
}
public virtual ConnectionSettings GetConnectionSettings(ConnectionSettings recent)
{
if (Builder != null)
{
var cs = ConnectionSettings.New();
Builder(cs);
return cs;
}
throw new NotImplementedException($"Template for '{Template}' is not implemented.");
}
}
public enum QuickActionTemplate
{
Undefined,
ClientTCPv4,
ServerTCPv4,
TunnelTCPv4,
Sniffer,
Monitor
}
public class QuickActionGroupDescription : GroupDescription
{
public static QuickActionGroupDescription Default { get; } = new QuickActionGroupDescription();
public override object GroupNameFromItem(object item, int level, CultureInfo culture)
{
if (item is RecentlyUsedItem recent)
{
var cs = recent.ConnectionSettings;
var dt = cs.CreatedAt.Date;
var now = DateTime.Now.Date;
var yesterday = now.AddDays(-1);
var thisWeekStart = now.LastDayOfWeek(DayOfWeek.Monday);
var lastWeekStart = thisWeekStart.AddDays(-7);
var thisMonthStart = new DateTime(now.Year, now.Month, 1);
var lastMonthStart = thisMonthStart.AddMonths(-1);
if (dt > now)
return "Future";
if (dt == now)
return "Today";
if (dt >= yesterday)
return "Yesterday";
if (dt >= thisWeekStart)
return "This week";
if (dt >= lastWeekStart)
return "Last week";
if (dt >= thisMonthStart)
return "This month";
if (dt >= lastMonthStart)
return "Last month";
return "Older";
}
else if (item is QuickActionItem)
{
return "Create new";
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace NetFabric.Hyperlinq
{
public static partial class ArrayExtensions
{
[GeneratorMapping("TPredicate", "NetFabric.Hyperlinq.FunctionInWrapper<TSource, int, bool>")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static ReadOnlyMemoryWhereAtRefEnumerable<TSource, FunctionInWrapper<TSource, int, bool>> Where<TSource>(this ReadOnlyMemory<TSource> source, FunctionIn<TSource, int, bool> predicate)
=> source.WhereAtRef(new FunctionInWrapper<TSource, int, bool>(predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static ReadOnlyMemoryWhereAtRefEnumerable<TSource, TPredicate> WhereAtRef<TSource, TPredicate>(this ReadOnlyMemory<TSource> source, TPredicate predicate = default)
where TPredicate : struct, IFunctionIn<TSource, int, bool>
=> new(source, predicate);
[GeneratorIgnore]
[StructLayout(LayoutKind.Auto)]
public readonly struct ReadOnlyMemoryWhereAtRefEnumerable<TSource, TPredicate>
where TPredicate : struct, IFunctionIn<TSource, int, bool>
{
internal readonly ReadOnlyMemory<TSource> source;
internal readonly TPredicate predicate;
internal ReadOnlyMemoryWhereAtRefEnumerable(ReadOnlyMemory<TSource> source, TPredicate predicate)
=> (this.source, this.predicate) = (source, predicate);
public readonly WhereAtReadOnlyRefEnumerator<TSource, TPredicate> GetEnumerator()
=> new (source.Span, predicate);
public bool SequenceEqual(IEnumerable<TSource> other, IEqualityComparer<TSource>? comparer = null)
{
if (Utils.UseDefault(comparer))
{
var enumerator = GetEnumerator();
using var otherEnumerator = other.GetEnumerator();
while (true)
{
var thisEnded = !enumerator.MoveNext();
var otherEnded = !otherEnumerator.MoveNext();
if (thisEnded != otherEnded)
return false;
if (thisEnded)
return true;
if (!EqualityComparer<TSource>.Default.Equals(enumerator.Current, otherEnumerator.Current))
return false;
}
}
else
{
comparer ??= EqualityComparer<TSource>.Default;
var enumerator = GetEnumerator();
using var otherEnumerator = other.GetEnumerator();
while (true)
{
var thisEnded = !enumerator.MoveNext();
var otherEnded = !otherEnumerator.MoveNext();
if (thisEnded != otherEnded)
return false;
if (thisEnded)
return true;
if (!comparer.Equals(enumerator.Current, otherEnumerator.Current))
return false;
}
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Sum<TPredicate>(this ReadOnlyMemoryWhereAtRefEnumerable<int, TPredicate> source)
where TPredicate : struct, IFunctionIn<int, int, bool>
=> source.source.Span.SumAtRef<int, int, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Sum<TPredicate>(this ReadOnlyMemoryWhereAtRefEnumerable<int?, TPredicate> source)
where TPredicate : struct, IFunctionIn<int?, int, bool>
=> source.source.Span.SumAtRef<int?, int, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long Sum<TPredicate>(this ReadOnlyMemoryWhereAtRefEnumerable<long, TPredicate> source)
where TPredicate : struct, IFunctionIn<long, int, bool>
=> source.source.Span.SumAtRef<long, long, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long Sum<TPredicate>(this ReadOnlyMemoryWhereAtRefEnumerable<long?, TPredicate> source)
where TPredicate : struct, IFunctionIn<long?, int, bool>
=> source.source.Span.SumAtRef<long?, long, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sum<TPredicate>(this ReadOnlyMemoryWhereAtRefEnumerable<float, TPredicate> source)
where TPredicate : struct, IFunctionIn<float, int, bool>
=> source.source.Span.SumAtRef<float, float, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sum<TPredicate>(this ReadOnlyMemoryWhereAtRefEnumerable<float?, TPredicate> source)
where TPredicate : struct, IFunctionIn<float?, int, bool>
=> source.source.Span.SumAtRef<float?, float, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Sum<TPredicate>(this ReadOnlyMemoryWhereAtRefEnumerable<double, TPredicate> source)
where TPredicate : struct, IFunctionIn<double, int, bool>
=> source.source.Span.SumAtRef<double, double, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Sum<TPredicate>(this ReadOnlyMemoryWhereAtRefEnumerable<double?, TPredicate> source)
where TPredicate : struct, IFunctionIn<double?, int, bool>
=> source.source.Span.SumAtRef<double?, double, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static decimal Sum<TPredicate>(this ReadOnlyMemoryWhereAtRefEnumerable<decimal, TPredicate> source)
where TPredicate : struct, IFunctionIn<decimal, int, bool>
=> source.source.Span.SumAtRef<decimal, decimal, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static decimal Sum<TPredicate>(this ReadOnlyMemoryWhereAtRefEnumerable<decimal?, TPredicate> source)
where TPredicate : struct, IFunctionIn<decimal?, int, bool>
=> source.source.Span.SumAtRef<decimal?, decimal, TPredicate>(source.predicate);
}
}
|
using JKMPCL.Model;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace JKMPCL.Services
{
/// <summary>
/// Class Name : UtilityPCL
/// Author : Hiren Patel
/// Creation Date : 10 Dec 2017
/// Purpose : For common validation and other stuff
/// Revision :
/// </summary>
public static class UtilityPCL
{
public static CustomerModel LoginCustomerData { get; set; }
public static MoveDataModel CustomerMoveData { get; set; }
public static string selectedMoveNumber { get; set; }
public static DocumentModel selectedDocumentModel { get; set; }
public enum CardType
{
Unknown,
MasterCard,
VISA,
Amex,
Discover,
DinersClub,
JCB,
enRoute
}
/// <summary>
/// Method Name : SetLoginCustomerProfileData
/// Author : Hiren Patel
/// Creation Date : 2 Dec 2017
/// Purpose : To store cutomer information as login customer data
/// Revision :
/// </summary>
public static void SetLoginCustomerProfileData(CustomerModel customerModel)
{
LoginCustomerData.CodeValidTill = customerModel.CodeValidTill;
LoginCustomerData.CustomerId = customerModel.CustomerId;
LoginCustomerData.EmailId = customerModel.EmailId;
LoginCustomerData.IsCustomerRegistered = customerModel.IsCustomerRegistered;
LoginCustomerData.LastLoginDate = customerModel.LastLoginDate;
LoginCustomerData.PasswordHash = customerModel.PasswordHash;
LoginCustomerData.PasswordSalt = customerModel.PasswordSalt;
LoginCustomerData.Phone = customerModel.Phone;
LoginCustomerData.PreferredContact = customerModel.PreferredContact;
LoginCustomerData.ReceiveNotifications = customerModel.ReceiveNotifications;
LoginCustomerData.TermsAgreed = customerModel.TermsAgreed;
LoginCustomerData.VerificationCode = customerModel.VerificationCode;
LoginCustomerData.CustomerFullName = customerModel.CustomerFullName;
}
/// <summary>
/// Method Name : SetCustomerMoveData
/// Author : Hiren Patel
/// Creation Date : 2 Dec 2017
/// Purpose : To store cutomer move information
/// Revision :
/// </summary>
public static void SetCustomerMoveData(GetMoveDataResponse moveDataModel)
{
if (moveDataModel is null)
{
return;
}
else
{
SetMoveData(moveDataModel);
SetMyServiceModel(moveDataModel);
SetDaysLeft(moveDataModel);
}
}
/// <summary>
/// Method Name : SetMyServiceModel
/// Author : Vivek Bhavsar
/// Creation Date : 22 Dec 2017
/// Purpose : Bind service list in customer move model
/// Revision : Modified by Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// </summary>
/// <param name="moveDataModel"></param>
private static void SetMyServiceModel(GetMoveDataResponse moveDataModel)
{
try
{
CustomerMoveData.MyServices = new List<MyServicesModel>();
if (moveDataModel.MyServices != null && moveDataModel.MyServices.Count > 0)
{
MyServicesModel myServiceModel;
foreach (MyServices myService in moveDataModel.MyServices)
{
myServiceModel = new MyServicesModel { ServicesCode = myService.ServicesCode };
CustomerMoveData.MyServices.Add(myServiceModel);
}
}
}
catch
{
//To be implemented
}
}
/// <summary>
/// Method Name : SetDaysLeft
/// Author : Vivek Bhavsar
/// Creation Date : 22 Dec 2017
/// Purpose : Bind days diff between load start & end date to customer move model days left
/// Revision : Modified by Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// </summary>
/// <param name="moveDataModel"></param>
private static void SetDaysLeft(GetMoveDataResponse moveDataModel)
{
try
{
if (string.IsNullOrEmpty(moveDataModel.MoveStartDate) && string.IsNullOrEmpty(moveDataModel.MoveEndDate))
{
DateTime firstLoadDate = Convert.ToDateTime(moveDataModel.MoveStartDate);
DateTime lastLoadDate = Convert.ToDateTime(moveDataModel.MoveEndDate);
CustomerMoveData.daysLeft = Convert.ToString((firstLoadDate - lastLoadDate).TotalDays);
}
}
catch
{
CustomerMoveData.daysLeft = "";
}
}
/// <summary>
/// Method Name : SetMoveData
/// Author : Vivek Bhavsar
/// Creation Date : 22 Dec 2017
/// Purpose : Bind Move data to customer move model
/// Revision : Modified by Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// </summary>
/// <param name="moveDataModel"></param>
private static void SetMoveData(GetMoveDataResponse moveDataModel)
{
try
{
if (CustomerMoveData is null)
CustomerMoveData = new MoveDataModel();
CustomerMoveData.MoveId = moveDataModel.MoveId;
CustomerMoveData.MoveNumber = moveDataModel.MoveNumber;
CustomerMoveData.IsActive = moveDataModel.IsActive;
CustomerMoveData.StatusReason = moveDataModel.StatusReason;
CustomerMoveData.Destination_City = moveDataModel.Destination_City;
CustomerMoveData.CustomDestinationAddress = moveDataModel.CustomDestinationAddress;
CustomerMoveData.Origin_City = moveDataModel.Origin_City;
CustomerMoveData.CustomOriginAddress = moveDataModel.CustomOriginAddress;
CustomerMoveData.MoveStartDate = moveDataModel.MoveStartDate;
CustomerMoveData.MoveEndDate = moveDataModel.MoveEndDate;
CustomerMoveData.WhatMattersMost = moveDataModel.WhatMattersMost;
CustomerMoveData.ExcessValuation = moveDataModel.ExcessValuation;
CustomerMoveData.ValuationDeductible = moveDataModel.ValuationDeductible;
CustomerMoveData.ValuationCost = moveDataModel.ValuationCost;
CustomerMoveData.ServiceCode = moveDataModel.ServiceCode;
}
catch
{
//To be implemented
}
}
/// <summary>
/// Method Name : RefreshCustomerProfileData
/// Author : Sanket Prajapati
/// Creation Date : 2 Dec 2017
/// Purpose : for Refresh Customer profile Data
/// Revision :
/// </summary>
public async static Task<string> RefreshCustomerProfileData()
{
LoginAPIServies loginAPIServies = new LoginAPIServies();
APIResponse<CustomerModel> response = await loginAPIServies.GetCustomerProfileData(LoginCustomerData);
if (!response.STATUS)
{
return response.Message;
}
else
{
return string.Empty;
}
}
/// <summary>
/// Method Name : ValidateEmail
/// Author : Sanket Prajapati
/// Creation Date : 2 Dec 2017
/// Purpose : Check Valid Email Address
/// Revision :
/// </summary>
public static bool ValidateEmail(string strEmail)
{
Regex regex;
Match match;
regex = new Regex(Resource.EmailRegex);
match = regex.Match(strEmail);
return match.Success;
}
/// <summary>
/// Method Name : GetMoveDataDispalyValue
/// Author : Sanket Prajapati
/// Creation Date : 27 Dec 2017
/// Purpose : for Display Move Data Value agains Move Data Code
/// Revision : By Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// </summary>
public static string GetMoveDataDisplayValue(string keyName, string keytype)
{
string resourceValue = string.Empty;
try
{
if (string.IsNullOrEmpty(keyName))
{
return keyName;
}
else
{
resourceValue = MoveDataDisplayResource.ResourceManager.GetString(keytype + keyName);
return resourceValue;
}
}
catch
{
return resourceValue;
}
}
/// <summary>
/// Method Name : CurrencyFormat
/// Author : Hiren Patel
/// Creation Date : 27 Dec 2017
/// Purpose : display currency in en-us particular format
/// Revision : By Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string CurrencyFormat(string text)
{
try
{
if (string.IsNullOrEmpty(text))
{
return 0.ToString("C", new CultureInfo("en-US"));
}
else
{
text = RemoveCurrencyFormat(text);
return Convert.ToDecimal(text).ToString("C", new CultureInfo("en-US"));
}
}
catch
{
return string.Empty;
}
}
/// <summary>
/// Method Name : CurrencyFormat
/// Author : Hiren Patel
/// Creation Date : 27 Dec 2017
/// Purpose : display currency in en-us particular format
/// Revision : By Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string RemoveCurrencyFormat(string text)
{
try
{
if (!string.IsNullOrEmpty(text))
{
text = text.Replace("$", string.Empty);
text = text.Replace(",", string.Empty);
return text;
}
else
{
return "0";
}
}
catch
{
return string.Empty;
}
}
/// <summary>
/// Method Name : CalulateMoveDays
/// Author : Hiren Patel
/// Creation Date : 27 Dec 2017
/// Purpose : Calculate days for Move
/// Revision : By Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// </summary>
/// <param name="startDate"></param>
/// <returns></returns>
public static string CalulateMoveDays(DateTime startDate)
{
string leftDays = string.Empty;
DateTime currentDate;
try
{
currentDate = ConvertDateTimeInUSFormat(DateTime.Today);
if (startDate <= currentDate)
{
leftDays = string.Empty;
}
else
{
int days = (startDate - currentDate).Days;
if (days < 10 && days > 0)
{
leftDays = string.Format("0{0}", days);
}
else
{
leftDays = string.Format("{0}", days);
}
}
return leftDays;
}
catch
{
return leftDays;
}
}
/// <summary>
/// Method Name : ConvertDateTimeInUSFormat
/// Author : Hiren Patel
/// Creation Date : 27 Dec 2017
/// Purpose : Convert string date into US format datetime
/// Revision : By Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime ConvertDateTimeInUSFormat(string dateTime)
{
try
{
if (string.IsNullOrEmpty(dateTime))
{
return DateTime.MinValue;
}
else
{
return Convert.ToDateTime(dateTime, new CultureInfo("en-US"));
}
}
catch
{
return DateTime.MinValue;
}
}
/// <summary>
/// Method Name : ConvertDateTimeInUSFormat
/// Author : Hiren Patel
/// Creation Date : 27 Dec 2017
/// Purpose : Convert date into US format datetime
/// Revision : By Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime ConvertDateTimeInUSFormat(DateTime dateTime)
{
try
{
return Convert.ToDateTime(dateTime, new CultureInfo("en-US"));
}
catch
{
return DateTime.MinValue;
}
}
/// <summary>
/// Method Name : DisplayDateFormatForEstimate
/// Author : Hiren Patel
/// Creation Date : 15 Jan 2018
/// Purpose : Display date in to specific format (Aknowledgement screen in estimates)
/// Revision :
/// </summary>
/// <param name="dateTime"></param>
/// <param name="dateFormat"></param>
/// <returns></returns>
public static string DisplayDateFormatForEstimate(DateTime? dateTime, string dateFormat)
{
if (dateTime.HasValue)
{
return (dateTime.Value.Month.ToString("00") + "/" + dateTime.Value.Day.ToString("00") + "/" + dateTime.Value.Year).ToString();
}
else
{
return string.Empty;
}
}
/// <summary>
/// Method Name : ValidateCreditCard
/// Author : Vivek Bhavsar
/// Creation Date : 31 Jan 2018
/// Purpose : check for credit card no by validating it with regular expreession
/// Revision : By Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// Revision : By Jitendra Garg on 20 Feb 2018 : Update the regex to include 12-19 characters, instead of validating for just Visa and Mastercard
/// </summary>
/// <param name="ValidateCreditCard"></param>
/// <returns></returns>
public static bool ValidateCard(string creditCardNumber)
{
try
{
Regex regexCard = new Regex(Resource.CreditCardValidationRegex);
Match match = regexCard.Match(creditCardNumber);
return match.Success;
}
catch
{
return false;
}
}
/// <summary>
/// Method Name : GetCardType
/// Author : Vivek Bhavsar
/// Creation Date : 31 Jan 2018
/// Purpose : get type of card VISA,MASTER etc.
/// Revision : By Vivek Bhavsar on 05 Feb 2018 : Add try catch block
/// https://stackoverflow.com/questions/72768/how-do-you-detect-credit-card-type-based-on-number
/// </summary>
/// <param name="creditCardNumber"></param>
/// <returns></returns>
public static CardType GetCardType(string creditCardNumber)
{
try
{
creditCardNumber = creditCardNumber.Replace("-", "").Replace(" ", "").Trim();
foreach (CardTypeInfoModel cardType in GetCardTypes())
{
if (Regex.IsMatch(creditCardNumber, cardType.Regex))
{
return cardType.CardType;
}
}
return CardType.Unknown;
}
catch
{
return CardType.Unknown;
}
}
/// <summary>
/// Method Name : GetCardTypes
/// Author : Vivek Bhavsar
/// Creation Date : 31 Jan 2018
/// Purpose : list of card types
/// Revision :
/// </summary>
/// <returns></returns>
public static List<CardTypeInfoModel> GetCardTypes()
{
List<CardTypeInfoModel> cardTypeInfo = new List<CardTypeInfoModel>();
cardTypeInfo.Add(new CardTypeInfoModel { Regex = Resource.MasterCardTypeRegex, CardNumberLength = 16, CardType = CardType.MasterCard });
cardTypeInfo.Add(new CardTypeInfoModel { Regex = Resource.VisaCardTypeRegex, CardNumberLength = 16, CardType = CardType.VISA });
cardTypeInfo.Add(new CardTypeInfoModel { Regex = Resource.VisaCardTypeRegex, CardNumberLength = 13, CardType = CardType.VISA });
return cardTypeInfo;
}
/// <summary>
/// Method Name : DisplayPhoneFormat
/// Author : Hiren Patel
/// Creation Date : 15 Jan 2018
/// Purpose : Display phone number in US format
/// Revision :
/// </summary>
/// <param name="phoneNumer"></param>
/// <returns></returns>
public static string DisplayPhoneFormat(string phoneNumer)
{
string formatedNumber = string.Empty;
try
{
if (string.IsNullOrEmpty(phoneNumer))
{
return formatedNumber;
}
else
{
var numbers = Regex.Replace(phoneNumer, @"\D", "");
if (numbers.Length <= 3)
{
formatedNumber = numbers;
}
else if (numbers.Length <= 7)
{
formatedNumber = string.Format("({0}) {1}", numbers.Substring(0, 3), numbers.Substring(3));
}
else
{
formatedNumber = string.Format("({0}) {1}-{2}", numbers.Substring(0, 3), numbers.Substring(3, 3), numbers.Substring(6, 4));
}
}
return formatedNumber;
}
catch (Exception)
{
return formatedNumber;
}
}
public static string DisplayCraditCardFormat(string CardNumer)
{
string formatedNumber = string.Empty;
try
{
if (string.IsNullOrEmpty(CardNumer))
{
return formatedNumber;
}
else
{
var numbers = Regex.Replace(CardNumer, @"\D", "");
if (numbers.Length == 4)
{
formatedNumber = string.Format("{0}-", numbers.Substring(0, 4));
}
else if (numbers.Length == 9)
{
formatedNumber = string.Format("{0}-{1}", numbers.Substring(0, 4), numbers.Substring(4));
}
else if (numbers.Length == 13)
{
formatedNumber = string.Format("{0}-{1}-{2}", numbers.Substring(0, 4), numbers.Substring(9, 4), numbers.Substring(13, 4));
}
}
return formatedNumber;
}
catch (Exception)
{
return formatedNumber;
}
}
public static bool IsMoveActive(string moveStatusCode)
{
if (MoveDataDisplayResource.MoveActiveCodeStatus == moveStatusCode)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Method Name : IsNullOrEmptyOrWhiteSpace
/// Author : Hiren Patel
/// Creation Date : 20 Jan 2018
/// Purpose : Is the null or empty or white space.
/// Revision :
/// </summary>
/// <returns><c>true</c>, if null or empty or white space, <c>false</c> otherwise.</returns>
/// <param name="value">Value.</param>
public static bool IsNullOrEmptyOrWhiteSpace(string value)
{
return (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value));
}
public static List<ValuationDeductibleModel> ValuationDeductibleList()
{
List<ValuationDeductibleModel> valueList;
valueList = new List<ValuationDeductibleModel>();
valueList.Add(new ValuationDeductibleModel() { Index = 0, DeductibleCode = MoveDataDisplayResource.Deductible10000000, DeductibleName = MoveDataDisplayResource.ValuationDeductible10000000 });
valueList.Add(new ValuationDeductibleModel() { Index = 1, DeductibleCode = MoveDataDisplayResource.Deductible100000001, DeductibleName = MoveDataDisplayResource.ValuationDeductible100000001 });
valueList.Add(new ValuationDeductibleModel() { Index = 2, DeductibleCode = MoveDataDisplayResource.Deductible100000002, DeductibleName = MoveDataDisplayResource.ValuationDeductible100000002 });
valueList.Add(new ValuationDeductibleModel() { Index = 3, DeductibleCode = MoveDataDisplayResource.Deductible100000003, DeductibleName = MoveDataDisplayResource.ValuationDeductible100000003 });
valueList.Add(new ValuationDeductibleModel() { Index = 4, DeductibleCode = MoveDataDisplayResource.Deductible100000004, DeductibleName = MoveDataDisplayResource.ValuationDeductible100000004 });
return valueList;
}
/// <summary>
/// Method Name : ValuationDeductibleBindingList
/// Author : Hiren Patel
/// Creation Date : 20 Jan 2018
/// Purpose : return list of valuation deductible codes from MoveDataDisplayResource
/// Revision :
/// </summary>
public static List<String> ValuationDeductibleBindingList()
{
List<String> valutionList = new List<String>();
valutionList.Add(MoveDataDisplayResource.ValuationDeductible10000000.Trim());
valutionList.Add(MoveDataDisplayResource.ValuationDeductible100000001.Trim());
valutionList.Add(MoveDataDisplayResource.ValuationDeductible100000002.Trim());
valutionList.Add(MoveDataDisplayResource.ValuationDeductible100000003.Trim());
valutionList.Add(MoveDataDisplayResource.ValuationDeductible100000004.Trim());
return valutionList;
}
public static List<MonthYearModel> BindMonthList()
{
MonthYearModel monthYearModel;
List<MonthYearModel> monthList;
monthList = new List<MonthYearModel>();
for (int i = 1; i <= 12; i++)
{
monthYearModel = new MonthYearModel();
monthYearModel.Month = i.ToString("00");
monthYearModel.Monthindex = i;
monthList.Add(monthYearModel);
}
return monthList;
}
public static List<String> MonthList()
{
List<String> monthList = new List<String>();
for (int i = 1; i <=12; i++)
{
string value;
value = i.ToString("00");
monthList.Add(value);
}
return monthList;
}
public static List<String> YearList()
{
List<String> yearList = new List<String>();
int year = DateTime.Now.Year;
for (int i = 0; i <= 40; i++)
{
int add = year + i;
yearList.Add(add.ToString());
}
return yearList;
}
public static List<MonthYearModel> BindYearList()
{
MonthYearModel monthYearModel;
List<MonthYearModel> yearList;
yearList = new List<MonthYearModel>();
int year = DateTime.Now.Year;
for (int i = 0; i <= 40; i++)
{
int addYear = year + i;
monthYearModel = new MonthYearModel();
monthYearModel.Year = addYear.ToString();
monthYearModel.Yearindex = addYear;
yearList.Add(monthYearModel);
}
return yearList;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWinPhone8.Classes.Domain
{
class VelocidadeException : Exception
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace AnimeViewer.Controls
{
public class ViewCellButton : Button
{
}
}
|
namespace _12.LegendaryFarming
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Startup
{
public static void Main(string[] args)
{
var items = new Dictionary<string, string>();
var material = new Dictionary<string, int>();
var othetMaterial = new Dictionary<string, int>();
var winner = string.Empty;
items.Add("shards", "Shadowmourne");
items.Add("fragments", "Valanyr");
items.Add("motes", "Dragonwrath");
material.Add("shards", 0);
material.Add("fragments", 0);
material.Add("motes", 0);
while (winner == string.Empty)
{
var arguments = Console.ReadLine()
.Trim()
.ToLower()
.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
for (int i = 0; i < arguments.Length; i++)
{
var quantity = int.Parse(arguments[i]);
var argMaterial = arguments[++i];
switch (argMaterial)
{
case "shards":
case "fragments":
case "motes":
material[argMaterial] += quantity;
if (winner == string.Empty && material[argMaterial] >= 250)
{
winner = argMaterial;
material[argMaterial] -= 250;
}
break;
default:
if (othetMaterial.ContainsKey(argMaterial))
{
othetMaterial[argMaterial] += quantity;
}
else
{
othetMaterial[argMaterial] = quantity;
}
break;
}
if (winner != string.Empty)
{
break;
}
}
}
Console.WriteLine($"{items[winner]} obtained!");
foreach (var m in material.OrderByDescending(x => x.Value).ThenBy(x => x.Key))
{
Console.WriteLine($"{m.Key}: {m.Value}");
}
foreach (var o in othetMaterial.OrderBy(x => x.Key))
{
Console.WriteLine($"{o.Key}: {o.Value}");
}
}
}
}
|
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
namespace Clime.ViewModel
{
public class LoginViewModel : ViewModelBase
{
public LoginViewModel()
{
Messenger.Default.Register<string>(this, SaveNewMeasurement);
}
private void SaveNewMeasurement(string message)
{
if (message.Equals("LoginMessage"))
{
var newView = new View.MainView();
newView.Show();
}
}
}
} |
using HelperLibrary.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using ConnectLibrary.Logger;
using ConnectLibrary.SQLRepository.Interfaces;
using ConnectLibrary.SQLRepository;
using MediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue;
using static ConnectLibrary.LibrarySettings;
namespace ConnectLibrary.Service
{
public class CommonService
{
private readonly ICommonRepository _commonRepository;
public CommonService()
{
_commonRepository = SetCommonRepository;
}
public IEnumerable<IGrouping<string, CommonModel>> FindStudentGrades()
{
var allGrades = _commonRepository.FindAllStudentGrades();
var groupedGrades = from students in allGrades group students by students.St_Last_Name;
return groupedGrades;
}
public IEnumerable<IGrouping<string, CommonModel>> GetStudentsByLecture(string subject, string lecturer)
{
if (subject == null)
{
Log.MakeLog(LoggerOperations.Error, "Argument null exception");
throw new ArgumentNullException(nameof(subject));
}
if (lecturer == null)
{
Log.MakeLog(LoggerOperations.Error, "Argument null exception");
throw new ArgumentNullException(nameof(lecturer));
}
return _commonRepository.GetStudentsOfLecturer(subject, lecturer).GroupBy(students => students.St_Last_Name + " " + students.St_First_Name);
}
public IEnumerable<IGrouping<string, CommonModel>> GetStudentsByLastName(string name)
{
if (name == null)
{
Log.MakeLog(LoggerOperations.Error, "Argument null exception");
throw new ArgumentNullException(nameof(name));
}
return _commonRepository.GetLectionOfStudent(name)
.GroupBy(students => students.Le_Last_Name + " " + students.Title);
}
public IEnumerable<string> GetAmountOfVisitedLections(string name, bool createRaport = false, FileFormat format = FileFormat.txt)
{
if (name == null)
{
Log.MakeLog(LoggerOperations.Error, "Argument null exception");
throw new ArgumentNullException(nameof(name));
}
var amountOfLectionsVisited = _commonRepository.GetAmountOfVisitedLections(name);
if (createRaport)
{
CreateFileRaport(amountOfLectionsVisited, name, format);
Log.MakeLog(LoggerOperations.Info, "File has been created");
}
return amountOfLectionsVisited;
}
public IEnumerable<string> GetAmountOfVisitedLections(string subject, string lecturer, bool createRaport = false, FileFormat format = FileFormat.txt)
{
if (subject == null) throw new ArgumentNullException(nameof(subject));
if (lecturer == null) throw new ArgumentNullException(nameof(lecturer));
var amountOfLectionsVisited = _commonRepository.GetAmountOfVisitedLections(subject, lecturer);
if (createRaport)
{
CreateFileRaport(amountOfLectionsVisited, $"{subject}-{lecturer}", format);
Log.MakeLog(LoggerOperations.Info, "File has been created");
}
return amountOfLectionsVisited;
}
public void CreateFileRaport(IEnumerable<string> raport, string filename, FileFormat format, string path = null)
{
string _path;
if (raport == null)
{
Log.MakeLog(LoggerOperations.Error, "Argument null exception");
throw new ArgumentNullException(nameof(raport));
}
if (filename == null)
{
Log.MakeLog(LoggerOperations.Error, "Argument null exception");
throw new ArgumentNullException(nameof(filename));
}
if (path == null)
{
var systemPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
_path = Path.Combine(systemPath , "Raports");
}
else
{
_path = path;
}
if (!Directory.Exists(_path))
{
Directory.CreateDirectory(_path);
}
//Creates file on Desktop
using (StreamWriter outputFile = new StreamWriter(Path.Combine(_path, $"{filename}.{format}")))
{
foreach (var listOfResult in raport)
{
outputFile.WriteLine(listOfResult);
}
}
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Reserva.Infra.Migrations
{
public partial class initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Filia",
columns: table => new
{
FilialId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Nome = table.Column<string>(maxLength: 100, nullable: false),
QuantidadeSala = table.Column<int>(nullable: false),
SalaId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Filia", x => x.FilialId);
table.UniqueConstraint("AK_Filia_SalaId", x => x.SalaId);
});
migrationBuilder.CreateTable(
name: "Reservas",
columns: table => new
{
ReservaId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
DataInicio = table.Column<DateTime>(nullable: false),
HoraInicio = table.Column<DateTime>(nullable: false),
DataFim = table.Column<DateTime>(nullable: false),
HoraFim = table.Column<DateTime>(nullable: false),
Café = table.Column<bool>(nullable: false),
QuantidadePessoa = table.Column<int>(nullable: false),
UsuarioId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Reservas", x => x.ReservaId);
});
migrationBuilder.CreateTable(
name: "Usuarios",
columns: table => new
{
UsuarioId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Nome = table.Column<string>(maxLength: 100, nullable: false),
Email = table.Column<string>(nullable: true),
Senha = table.Column<string>(maxLength: 6, nullable: false),
User = table.Column<string>(maxLength: 50, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Usuarios", x => x.UsuarioId);
});
migrationBuilder.CreateTable(
name: "Sala",
columns: table => new
{
SalaId = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
NomeSala = table.Column<string>(nullable: false),
TipoSala = table.Column<int>(nullable: false),
FilialId = table.Column<int>(nullable: false),
ReservasReservaId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Sala", x => x.SalaId);
table.ForeignKey(
name: "FK_Sala_Filia_FilialId",
column: x => x.FilialId,
principalTable: "Filia",
principalColumn: "SalaId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Sala_Reservas_ReservasReservaId",
column: x => x.ReservasReservaId,
principalTable: "Reservas",
principalColumn: "ReservaId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Sala_FilialId",
table: "Sala",
column: "FilialId");
migrationBuilder.CreateIndex(
name: "IX_Sala_ReservasReservaId",
table: "Sala",
column: "ReservasReservaId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Sala");
migrationBuilder.DropTable(
name: "Usuarios");
migrationBuilder.DropTable(
name: "Filia");
migrationBuilder.DropTable(
name: "Reservas");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuHandler : MonoBehaviour
{
[SerializeField]
private List<GameObject> menus = new List<GameObject>();
private int activeMenuIndex;
private void Awake() {
ChangeMenu(0);
}
/// Call this to Change the menu in the array to the given number.
public void ChangeMenu(int menuIndex) {
for(int i = 0; i < menus.Count; i++) {
menus[i].SetActive(false);
}
if(menus[menuIndex] != null) {
menus[menuIndex].SetActive(true);
activeMenuIndex = menuIndex;
}
}
public void NextMenu() {
if(activeMenuIndex < menus.Count) {
ChangeMenu(activeMenuIndex++);
}
}
public void PreviousMenu() {
if(activeMenuIndex > 0) {
ChangeMenu(activeMenuIndex--);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.DataStudio.Diagnostics;
namespace MLApiClientTestApp.Models
{
// I basically use this to write to a TextBox control in my unit test app
public interface ITestLogger : ILogger
{
void WriteEmptyLineAsync();
void Clear();
}
}
|
using System.Collections.ObjectModel;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Threading.Tasks;
namespace CG_DatabaseReader
{
partial class MainWindow
{
private void ReadCustomerList()
{
ObservableCollection<Customer> list = new ObservableCollection<Customer>();
OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
csbuilder.DataSource = ExcelPath;
csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=NO");
using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
{
DataTable sheet1 = new DataTable();
connection.Open();
string sqlQuery = @"SELECT * FROM ['invoice schedule new$']";
using (OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery, connection))
{
adapter.Fill(sheet1);
for (int i = 3; i < sheet1.Rows.Count; i++)
{
if(!string.IsNullOrWhiteSpace(sheet1.Rows[i].ItemArray[1] as string))
{
Customer line = new Customer();
line.Debitor = "" + sheet1.Rows[i].ItemArray[0] as string;
line.Projects = "" + sheet1.Rows[i].ItemArray[1] as string;
line.Period = "" + sheet1.Rows[i].ItemArray[2] as string;
line.Product = "" + sheet1.Rows[i].ItemArray[4] as string;
line.Name = "" + sheet1.Rows[i].ItemArray[5] as string;
line.Zusatz = "" + sheet1.Rows[i].ItemArray[6] as string;
line.Strasse = "" + sheet1.Rows[i].ItemArray[7] as string;
line.Stadt = "" + sheet1.Rows[i].ItemArray[8] as string;
line.Country = "" + sheet1.Rows[i].ItemArray[9] as string;
line.Comment = "" + sheet1.Rows[i].ItemArray[10] as string;
line.TigerComms = "" + sheet1.Rows[i].ItemArray[11] as string;
line.SupportLevel = "" + sheet1.Rows[i].ItemArray[12] as string;
line.Contract = "" + sheet1.Rows[i].ItemArray[13] as string;
line.Warranty = "" + sheet1.Rows[i].ItemArray[14] as string;
line.Volume = "" + sheet1.Rows[i].ItemArray[15] as string;
list.Add(line);
Debug.WriteLine(i + " - " + line.Projects + " - " + line.Debitor);
}
}
}
connection.Close();
txtStatus.Text = "";
}
CustomerList = list;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Polite
{
public class Contact
{
public Contact(String csvLine)
{
string[] values = csvLine.Split(',');
this.FirstName = values[0];
this.LastName = values[1];
this.StreetNumber = int.Parse(values[2].Substring(0, values[2].IndexOf(" ")));
this.StreetName = values[2].Substring(values[2].IndexOf(" ")+1);
this.PhoneNumber = int.Parse(values[3]);
}
public string FirstName {get; set;}
public string LastName { get; set; }
public int StreetNumber{ get; set; }
public string StreetName { get; set; }
public int PhoneNumber { get; set; }
}
}
|
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Ayende Rahien nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Windows.Forms;
using Ayende.NHibernateQueryAnalyzer.SchemaEditing;
namespace Ayende.NHibernateQueryAnalyzer.UserInterface.SchemaEditing
{
public class WinFormsSchemaEditorNodeFactory:ISchemaEditorNodeFactory
{
SchemaEditorView view;
public WinFormsSchemaEditorNodeFactory(SchemaEditorView view)
{
this.view = view;
}
/// <summary>
/// Create a node that contains the obj as the internal value.
/// </summary>
public ISchemaEditorNode CreateNode(NodeFieldReference fieldReference, object obj, string name)
{
WinFormsSchemaEditorNode node = new WinFormsSchemaEditorNode(view, fieldReference,obj,name);
return node;
}
public ISchemaEditorNode CreateRoot(RootNodeFieldReference reference, object rootObj, string name)
{
ISchemaEditorNode node = CreateNode(reference, rootObj, name);
view.GraphTree.Nodes.Add((TreeNode)node);
return node;
}
}
}
|
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet.Ndr;
using NtApiDotNet.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace NtApiDotNet.Win32
{
internal enum RpcEndPointVersionOption
{
All = 1,
Compatible = 2,
Exact = 3,
MajorOnly = 4,
Upto = 5
}
internal enum RpcEndpointInquiryFlag
{
All = 0,
Interface = 1,
Object = 2,
Both = 3,
}
[StructLayout(LayoutKind.Sequential)]
internal class UUID
{
public Guid Uuid;
}
[StructLayout(LayoutKind.Sequential)]
internal class RPC_IF_ID
{
public Guid Uuid;
public ushort VersMajor;
public ushort VersMinor;
}
[StructLayout(LayoutKind.Sequential), DataStart("IfId")]
internal class RPC_IF_ID_VECTOR
{
public int Count;
public IntPtr IfId; // RPC_IF_ID*
};
/// <summary>
/// Static class to access information from the RPC mapper.
/// </summary>
public static class RpcEndpointMapper
{
#region Private Members
private static IEnumerable<RpcEndpoint> QueryEndpoints(string search_binding, RpcEndpointInquiryFlag inquiry_flag, RPC_IF_ID if_id_search, RpcEndPointVersionOption version, UUID uuid_search, bool throw_on_error = true)
{
using (SafeRpcBindingHandle search_handle = string.IsNullOrEmpty(search_binding) ? SafeRpcBindingHandle.Null : SafeRpcBindingHandle.Create(search_binding))
{
int status = Win32NativeMethods.RpcMgmtEpEltInqBegin(search_handle,
inquiry_flag,
if_id_search, version, uuid_search, out SafeRpcInquiryHandle inquiry);
if (status != 0)
{
if (throw_on_error)
throw new SafeWin32Exception(status);
yield break;
}
using (inquiry)
{
while (true)
{
RPC_IF_ID if_id = new RPC_IF_ID();
UUID uuid = new UUID();
status = Win32NativeMethods.RpcMgmtEpEltInqNext(inquiry, if_id, out SafeRpcBindingHandle binding, uuid, out SafeRpcStringHandle annotation);
if (status != 0)
{
if (status != 1772 && throw_on_error)
{
throw new SafeWin32Exception(status);
}
break;
}
try
{
yield return new RpcEndpoint(if_id, uuid, annotation, binding, true);
}
finally
{
binding.Dispose();
annotation.Dispose();
}
}
}
}
}
private static RpcEndpoint CreateEndpoint(SafeRpcBindingHandle binding_handle, RPC_IF_ID if_id)
{
var endpoints = QueryEndpoints(binding_handle.ToString(), RpcEndpointInquiryFlag.Interface,
if_id, RpcEndPointVersionOption.Exact, null, false).ToArray();
RpcEndpoint ret = endpoints.Where(ep => ep.BindingString.Equals(binding_handle.ToString(), StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
return ret ?? new RpcEndpoint(if_id, new UUID(), null, binding_handle, false);
}
private const string RPC_CONTROL_PATH = @"\RPC Control\";
private static IEnumerable<RpcEndpoint> QueryEndpointsForBinding(SafeRpcBindingHandle binding_handle)
{
using (binding_handle)
{
int status = Win32NativeMethods.RpcMgmtInqIfIds(binding_handle, out SafeRpcIfIdVectorHandle if_id_vector);
// If the RPC server doesn't exist return an empty list.
if (status == 1722)
{
return new RpcEndpoint[0];
}
if (status != 0)
{
throw new SafeWin32Exception(status);
}
using (if_id_vector)
{
return if_id_vector.GetIfIds().Select(if_id => CreateEndpoint(binding_handle, if_id)).ToArray();
}
}
}
private static Win32Error ResolveBinding(SafeRpcBindingHandle binding, Guid interface_id, Version interface_version)
{
RPC_SERVER_INTERFACE ifspec = new RPC_SERVER_INTERFACE();
ifspec.Length = Marshal.SizeOf(ifspec);
ifspec.InterfaceId.SyntaxGUID = interface_id;
ifspec.InterfaceId.SyntaxVersion = interface_version.ToRpcVersion();
return Win32NativeMethods.RpcEpResolveBinding(binding, ref ifspec);
}
private static string MapBindingToBindingString(NtResult<SafeRpcBindingHandle> binding, Guid interface_id, Version interface_version)
{
if (!binding.IsSuccess)
return string.Empty;
if (ResolveBinding(binding.Result, interface_id, interface_version) != Win32Error.SUCCESS)
{
return string.Empty;
}
return binding.Result.ToString();
}
#endregion
#region Static Methods
/// <summary>
/// Query all endpoints registered on the local system.
/// </summary>
/// <returns>List of endpoints.</returns>
public static IEnumerable<RpcEndpoint> QueryEndpoints()
{
return QueryEndpoints(null, RpcEndpointInquiryFlag.All, null, RpcEndPointVersionOption.All, null);
}
/// <summary>
/// Query all endpoints registered based on a binding string.
/// </summary>
/// <param name="search_binding">The binding string for the server to search on. If null or empty will search localhost.</param>
/// <returns>List of endpoints.</returns>
public static IEnumerable<RpcEndpoint> QueryEndpoints(string search_binding)
{
return QueryEndpoints(search_binding, RpcEndpointInquiryFlag.All, null, RpcEndPointVersionOption.All, null);
}
/// <summary>
/// Query for endpoints registered on the local system for an RPC endpoint.
/// </summary>
/// <param name="search_binding">The binding string for the server to search on. If null or empty will search localhost.</param>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <returns>The list of registered RPC endpoints.</returns>
public static IEnumerable<RpcEndpoint> QueryEndpoints(string search_binding, Guid interface_id, Version interface_version)
{
RPC_IF_ID if_id = new RPC_IF_ID()
{
Uuid = interface_id,
VersMajor = (ushort)interface_version.Major,
VersMinor = (ushort)interface_version.Minor
};
return QueryEndpoints(search_binding, RpcEndpointInquiryFlag.Interface, if_id, RpcEndPointVersionOption.Exact, null);
}
/// <summary>
/// Query for endpoints registered on the local system for an RPC endpoint.
/// </summary>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <returns>The list of registered RPC endpoints.</returns>
public static IEnumerable<RpcEndpoint> QueryEndpoints(Guid interface_id, Version interface_version)
{
return QueryEndpoints(null, interface_id, interface_version);
}
/// <summary>
/// Query for endpoints registered on the local system for an RPC endpoint ignoring the version.
/// </summary>
/// <param name="search_binding">The binding string for the server to search on. If null or empty will search localhost.</param>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <returns>The list of registered RPC endpoints.</returns>
public static IEnumerable<RpcEndpoint> QueryEndpoints(string search_binding, Guid interface_id)
{
RPC_IF_ID if_id = new RPC_IF_ID()
{
Uuid = interface_id
};
return QueryEndpoints(search_binding, RpcEndpointInquiryFlag.Interface, if_id, RpcEndPointVersionOption.All, null);
}
/// <summary>
/// Query for endpoints registered on the local system for an RPC endpoint ignoring the version.
/// </summary>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <returns>The list of registered RPC endpoints.</returns>
public static IEnumerable<RpcEndpoint> QueryEndpoints(Guid interface_id)
{
return QueryEndpoints(null, interface_id);
}
/// <summary>
/// Query for endpoints registered on the local system for an RPC endpoint.
/// </summary>
/// <param name="server_interface">The server interface.</param>
/// <returns>The list of registered RPC endpoints.</returns>
public static IEnumerable<RpcEndpoint> QueryEndpoints(NdrRpcServerInterface server_interface)
{
return QueryEndpoints(server_interface.InterfaceId, server_interface.InterfaceVersion);
}
/// <summary>
/// Query for endpoints registered on the local system for an RPC endpoint via ALPC.
/// </summary>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <returns>The list of registered RPC endpoints.</returns>
public static IEnumerable<RpcEndpoint> QueryAlpcEndpoints(Guid interface_id, Version interface_version)
{
RPC_IF_ID if_id = new RPC_IF_ID()
{
Uuid = interface_id,
VersMajor = (ushort)interface_version.Major,
VersMinor = (ushort)interface_version.Minor
};
return QueryEndpoints(null, RpcEndpointInquiryFlag.Interface, if_id,
RpcEndPointVersionOption.Exact, null).Where(e => e.ProtocolSequence.Equals("ncalrpc", StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Query for endpoints registered on the local system for an RPC endpoint via ALPC.
/// </summary>
/// <param name="server_interface">The server interface.</param>
/// <returns>The list of registered RPC endpoints.</returns>
public static IEnumerable<RpcEndpoint> QueryAlpcEndpoints(NdrRpcServerInterface server_interface)
{
return QueryAlpcEndpoints(server_interface.InterfaceId, server_interface.InterfaceVersion);
}
/// <summary>
/// Query for endpoints for a RPC binding.
/// </summary>
/// <param name="alpc_port">The ALPC port to query. Can be a full path as long as it contains \RPC Control\ somewhere.</param>
/// <returns>The list of endpoints on the RPC binding.</returns>
public static IEnumerable<RpcEndpoint> QueryEndpointsForAlpcPort(string alpc_port)
{
int index = alpc_port.IndexOf(@"\RPC Control\", StringComparison.OrdinalIgnoreCase);
if (index >= 0)
{
alpc_port = alpc_port.Substring(0, index) + RPC_CONTROL_PATH + alpc_port.Substring(index + RPC_CONTROL_PATH.Length);
}
return QueryEndpointsForBinding(SafeRpcBindingHandle.Create(null, "ncalrpc", null, alpc_port, null));
}
/// <summary>
/// Query for endpoints for a RPC binding.
/// </summary>
/// <param name="string_binding">The RPC binding to query, e.g. ncalrpc:[PORT]</param>
/// <returns>The list of endpoints on the RPC binding.</returns>
public static IEnumerable<RpcEndpoint> QueryEndpointsForBinding(string string_binding)
{
return QueryEndpointsForBinding(SafeRpcBindingHandle.Create(string_binding));
}
/// <summary>
/// Resolve the local binding string for this service from the local Endpoint Mapper and return the endpoint.
/// </summary>
/// <param name="protocol_seq">The protocol sequence to lookup.</param>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <returns>The mapped endpoint.</returns>
/// <remarks>This only will return a valid value if the service is running and registered with the Endpoint Mapper. It can also hang.</remarks>
public static RpcEndpoint MapServerToEndpoint(string protocol_seq, Guid interface_id, Version interface_version)
{
return MapServerToEndpoint(protocol_seq, null, interface_id, interface_version);
}
/// <summary>
/// Resolve the local binding string for this service from the local Endpoint Mapper and return the endpoint.
/// </summary>
/// <param name="protocol_seq">The protocol sequence to lookup.</param>
/// <param name="network_address">The network address for the lookup.</param>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <returns>The mapped endpoint.</returns>
/// <remarks>This only will return a valid value if the service is running and registered with the Endpoint Mapper. It can also hang.</remarks>
public static RpcEndpoint MapServerToEndpoint(string protocol_seq, string network_address, Guid interface_id, Version interface_version)
{
string binding = MapServerToBindingString(protocol_seq, network_address, interface_id, interface_version);
if (string.IsNullOrEmpty(binding))
{
return null;
}
return new RpcEndpoint(interface_id, interface_version, binding, true);
}
/// <summary>
/// Resolve the local binding string for this service from the local Endpoint Mapper and return the endpoint.
/// </summary>
/// <param name="string_binding">The string binding to map.</param>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <returns>The mapped endpoint.</returns>
/// <remarks>This only will return a valid value if the service is running and registered with the Endpoint Mapper. It can also hang.</remarks>
public static RpcEndpoint MapBindingStringToEndpoint(string string_binding, Guid interface_id, Version interface_version)
{
string binding = MapBindingToBindingString(string_binding, interface_id, interface_version);
if (string.IsNullOrEmpty(binding))
{
return null;
}
return new RpcEndpoint(interface_id, interface_version, binding, true);
}
/// <summary>
/// Resolve the local binding string for this service from the local Endpoint Mapper and return the ALPC port path.
/// </summary>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <returns>The mapped endpoint.</returns>
/// <remarks>This only will return a valid value if the service is running and registered with the Endpoint Mapper. It can also hang.</remarks>
public static RpcEndpoint MapServerToAlpcEndpoint(Guid interface_id, Version interface_version)
{
return MapServerToEndpoint("ncalrpc", interface_id, interface_version);
}
/// <summary>
/// Resolve the local binding string for this service from the local Endpoint Mapper and return the ALPC port path.
/// </summary>
/// <param name="server_interface">The server interface.</param>
/// <returns>The mapped endpoint.</returns>
/// <remarks>This only will return a valid value if the service is running and registered with the Endpoint Mapper. It can also hang.</remarks>
public static RpcEndpoint MapServerToAlpcEndpoint(NdrRpcServerInterface server_interface)
{
return MapServerToAlpcEndpoint(server_interface.InterfaceId, server_interface.InterfaceVersion);
}
/// <summary>
/// Finds ALPC endpoints which allows for the server binding. This brute forces all ALPC ports to try and find
/// something which will accept the bind.
/// </summary>
/// <remarks>This could hang if the ALPC port is owned by a suspended process.</remarks>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <returns>A list of RPC endpoints which can bind the interface.</returns>
/// <exception cref="NtException">Throws on error.</exception>
public static IEnumerable<RpcEndpoint> FindAlpcEndpointForInterface(Guid interface_id, Version interface_version)
{
using (var dir = NtDirectory.Open(@"\RPC Control"))
{
var nt_type = NtType.GetTypeByType<NtAlpc>().Name;
foreach (var port in dir.Query().Where(e => e.NtTypeName == nt_type))
{
bool success = false;
try
{
using (var server = new RpcClient(interface_id, interface_version))
{
server.Connect(port.Name);
success = true;
}
}
catch
{
}
if (success)
{
yield return new RpcEndpoint(interface_id, interface_version,
SafeRpcBindingHandle.Compose(null, "ncalrpc", null, port.Name, null), false);
}
}
}
}
/// <summary>
/// Finds an ALPC endpoint which allows for the server binding. This brute forces all ALPC ports to try and find
/// something which will accept the bind.
/// </summary>
/// <remarks>This could hang if the ALPC port is owned by a suspended process.</remarks>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <returns>The first RPC endpoints which can bind the interface. Throws exception if nothing found.</returns>
/// <exception cref="NtException">Throws on error.</exception>
public static RpcEndpoint FindFirstAlpcEndpointForInterface(Guid interface_id, Version interface_version)
{
return FindAlpcEndpointForInterface(interface_id, interface_version).First();
}
/// <summary>
/// Resolve the binding string for this service from the Endpoint Mapper.
/// </summary>
/// <param name="string_binding">The binding string to map.</param>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <remarks>This only will return a valid value if the service is running and registered with the Endpoint Mapper. It can also hang.</remarks>
/// <returns>The RPC binding string. Empty string if it doesn't exist or the lookup failed.</returns>
public static string MapBindingToBindingString(string string_binding, Guid interface_id, Version interface_version)
{
using (var binding = SafeRpcBindingHandle.Create(string_binding, false))
{
return MapBindingToBindingString(binding, interface_id, interface_version);
}
}
/// <summary>
/// Resolve the binding string for this service from the the Endpoint Mapper.
/// </summary>
/// <param name="protocol_seq">The protocol sequence to lookup.</param>
/// <param name="network_address">The network address to lookup the endpoint.</param>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <remarks>This only will return a valid value if the service is running and registered with the Endpoint Mapper. It can also hang.</remarks>
/// <returns>The RPC binding string. Empty string if it doesn't exist or the lookup failed.</returns>
public static string MapServerToBindingString(string protocol_seq, string network_address, Guid interface_id, Version interface_version)
{
using (var binding = SafeRpcBindingHandle.Create(null, protocol_seq, network_address, null, null, false))
{
return MapBindingToBindingString(binding, interface_id, interface_version);
}
}
/// <summary>
/// Resolve the binding string for this service from the local Endpoint Mapper.
/// </summary>
/// <param name="protocol_seq">The protocol sequence to lookup.</param>
/// <param name="interface_id">Interface UUID to lookup.</param>
/// <param name="interface_version">Interface version lookup.</param>
/// <remarks>This only will return a valid value if the service is running and registered with the Endpoint Mapper. It can also hang.</remarks>
/// <returns>The RPC binding string. Empty string if it doesn't exist or the lookup failed.</returns>
public static string MapServerToBindingString(string protocol_seq, Guid interface_id, Version interface_version)
{
return MapServerToBindingString(protocol_seq, null, interface_id, interface_version);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Vasily;
namespace VasilyTest
{
[Table("tablename")]
public class NormalTest : IVasily
{
[PrimaryKey]
public int ID;
public int? Age { get; set; }
[Repeate]
public int StudentId;
[Column("School Description")]
public string Desc;
[Column("Html Title")]
public string Title { get; set; }
public DateTime? UpdateTime {get;set;}
public DateTime CreateTime;
[Ignore]
public string JsonTime
{
get { return CreateTime.ToString("yyyy-MM-dd"); }
}
}
}
|
using UnityEngine;
using System.Collections;
// Terrain effect gotten from standing in a forest space
// Gives considerable ranged defence
public class Forest : Effect
{
public Forest(Unit receiver)
: base("Forest", "Arrows and stones are caught and deflected by thick tree limbs, providing excellent cover.", receiver)
{
this.terrain_effect = true;
}
public override void ApplyEffect()
{
base.ApplyEffect();
receiver.AdjustDefence(0.10f);
receiver.AdjustRangedDefence(0.50f);
}
public override Effect Clone(Unit receiving_unit)
{
return new Forest(receiving_unit);
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace CRUDelicious.Models
{
public class Dish
{
[Key]
public int DishId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Chef { get; set; }
[Required]
[Range(1,6,ErrorMessage = "Tastiness must be between 1 and 5")]
// asp net dropdown options & validdations select and sect
public int Tastiness { get; set; }
[Required]
[Range(1,int.MaxValue,ErrorMessage = "Calories must be greater than 0")]
public string Calories { get; set; }
[Required]
public string Description { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.Now;
public DateTime UpdatedAt { get; set; } = DateTime.Now;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Engine.Models;
namespace Engine.Factories
{
internal static class WorldFactory
{
internal static World CreateWorld()
{
World newWorld = new World();
newWorld.AddLocation(-2, -1, "Pole Farmera",
"Gdzieś wśród tych rzędów kukurydzy, chowa się wielki szczur!",
"/engine;component/Obrazy/Lokacje/PoleFarmera.png");
newWorld.LocationAt(-2, -1).AddMonster(2, 100);
newWorld.AddLocation(-1, -1, "Dom farmerski",
"Wokół pasą się krówki, a kogut przymierza się do dziobnięcia Cię w stopę.",
"/engine;component/Obrazy/Lokacje/Domfarmerski.png");
newWorld.LocationAt(-1, -1).QuestsAvailableHere.Add(QuestFactory.GetQuestByID(2));
newWorld.AddLocation(0, -1, "Dom",
"To twój dom!",
"/Engine;component/Obrazy/Lokacje/Dom.png");
newWorld.AddLocation(-1, 0, "Sklep z różnościami",
"Sklep z prawie 200 letnią historią, aktualnie prowadzony przez panią Elę.",
"/Engine;component/Obrazy/Lokacje/Sklep.png");
newWorld.AddLocation(0, 0, "Plac",
"Wrzuć pieniążka do fontanny, a wszystkie twoje życzenia się spełnią.",
"/Engine;component/Obrazy/Lokacje/Plac.png");
newWorld.AddLocation(1, 0, "Brama do miasta",
"Bez tej bramy, mieszkancy dawno zostaliby pożarci przez Wielkie Pająki.",
"/Engine;component/Obrazy/Lokacje/Brama.png");
newWorld.AddLocation(2, 0, "Pajęczy las",
"Wszystkie rośliny pokrytę są pajęczyną...",
"/Engine;component/Obrazy/Lokacje/Pajeczylas.png");
newWorld.LocationAt(2, 0).AddMonster(3, 100);
newWorld.AddLocation(0, 1, "Domek zielarki",
"Już z kilometra czuć intensywny zapach roślin, na ganku zapach jest nie do wytrzymania!.",
"/Engine;component/Obrazy/Lokacje/Domekzielarki.png");
newWorld.LocationAt(0, 1).QuestsAvailableHere.Add(QuestFactory.GetQuestByID(1));
newWorld.AddLocation(0, 2, "Ogród zielarki",
"Tu też woń kwiatów przyprawia o zawrót głowy, jedynie węże wydają się być odporne.",
"/Engine;component/Obrazy/Lokacje/ogrodzielarki.png");
newWorld.LocationAt(0, 2).AddMonster(1, 100);
return newWorld;
}
}
}
|
/*
.-'
'--./ / _.---.
'-, (__..-` \
\ . |
`,.__. ,__.--/
'._/_.'___.-`
FREE WILLY
*/
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using NLog;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
namespace Automatisation.ViewModel
{
/// <summary>
/// This class contains properties that a View can data bind to.
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
class AttenuatorsVM : ObservableObject
{
#region fields
private static Logger _log = LogManager.GetCurrentClassLogger();
private ObservableCollection<AttenuatorUCVM> _lstAtt;
private int _connectedDevices;
private uint[] _myDevices;
/// <summary>
/// 1 = testmode, 0 = look for real attenuators
/// </summary>
private int _isTestMode = 0;
private RelayCommand _cmdRefresh;
private RelayCommand _cmdStartAll;
private RelayCommand _cmdStopAll;
private RelayCommand _cmdManualNextStep;
#endregion fields
#region properties
/// <summary>
/// Observable collection to store found attenuators
/// </summary>
public ObservableCollection<AttenuatorUCVM> LstAtt { get { return _lstAtt; } set { if (value != _lstAtt) { _lstAtt = value; OnPropertyChanged("LstAtt"); } } }
/// <summary>
/// Ammount of connected attenuators
/// </summary>
public int ConnectedDevices
{
get { return _connectedDevices; }
set
{
if (value != _connectedDevices)
{
_connectedDevices = value;
MyDevices = new uint[ConnectedDevices];
Libs.VNX_Atten.GetDevInfo(MyDevices);
OnPropertyChanged("ConnectedDevices");
}
}
}
/// <summary>
/// Array of uint to store device ids.
/// </summary>
public uint[] MyDevices { get { return _myDevices; } set { if (value != _myDevices) { _myDevices = value; OnPropertyChanged("ConnectedDevices"); } } }
public RelayCommand CMDRefresh { get { return _cmdRefresh ?? (_cmdRefresh = new RelayCommand(RefreshAll)); } }
public RelayCommand CMDStartAll { get { return _cmdStartAll ?? (_cmdStartAll = new RelayCommand(StartAll)); } }
public RelayCommand CMDStopAll { get { return _cmdStopAll ?? (_cmdStopAll = new RelayCommand(StopAll)); } }
public RelayCommand CMDManualNextStep { get { return _cmdManualNextStep ?? (_cmdManualNextStep = new RelayCommand(NextStepAll)); } }
#endregion properties
#region constructor
/// <summary>
/// Initializes a new instance of the TabAttenuatorViewModel class.
/// </summary>
public AttenuatorsVM()
{
//Messenger.Default.Register<NotificationMessage>(this, (message) => NotificationMessageHandler(message));
}
#endregion constructor
/// <summary>
/// Enable attenuator functions: Look for attenuators and connect them
/// </summary>
public void EnableAttenuators()
{
if (_isTestMode == 1)
Messenger.Default.Send(new NotificationMessage(Messages.Messages.ATTENUATOR_TEST_MODE));
Libs.VNX_Atten.SetTestMode(_isTestMode);
//Task task = new Task(() =>
//{
LookForDevices();
ConnectAllDevices();
// });
//task.Start();
//if (_isTestMode == 1)
//GenerateExtraDevicedTestLayout();
}
private void GenerateExtraDevicedTestLayout()
{
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
LstAtt.Add(new AttenuatorUCVM());
}
/// <summary>
/// Disable attenuator functions: Disconnect every attenuator
/// </summary>
public void DisableAttenuators()
{
DisconnectAllDevices();
LstAtt.Clear();
LstAtt = null;
}
/// <summary>
/// Look for usb connected attenuators, create model object and add to a collection
/// </summary>
private void LookForDevices()
{
//get ammount of connected devices. If > 0 create an attuenator object for each device and add it to a collection
ConnectedDevices = Libs.VNX_Atten.GetNumDevices();
if (ConnectedDevices != 0)
{
LstAtt = new ObservableCollection<AttenuatorUCVM>();
foreach (uint dev in _myDevices)
{
AttenuatorUCVM att = new AttenuatorUCVM(dev);
LstAtt.Add(att);
}
}
}
/// <summary>
/// Loop through a collection of Attenuators and init every device
/// </summary>
private void ConnectAllDevices()
{
foreach (AttenuatorUCVM att in LstAtt)
{
att.StartConnection(); att.GetSettings();
}
}
/// <summary>
/// Loop through a collection of Attenuators and close the connection with every device
/// </summary>
private void DisconnectAllDevices()
{
foreach (AttenuatorUCVM att in LstAtt)
{
att.CloseConnection();
}
}
/// <summary>
/// Loop through a collection of Attenuators and close the connection with given device
/// </summary>
/// <param name="devid">Device id of the device to disconnect</param>
private void DisconnectDeviceRemoveFromList(uint devid)
{
foreach (AttenuatorUCVM att in LstAtt)
{
if (att.DevID == devid)
{
att.CloseConnection();
LstAtt.Remove(att);
}
}
}
/// <summary>
/// Get Attenuator object from list by device id
/// </summary>
/// <param name="devid"></param>
/// <returns></returns>
private AttenuatorUCVM GetAttByIdFromList(uint devid)
{
foreach (AttenuatorUCVM att in LstAtt)
{
if (att.DevID == devid)
{
return att;
}
}
return null;
}
/// <summary>
/// Loop through a collection of Attenuators and set settings to zero for every device
/// </summary>
/// <param name="devid"></param>
private void ResetToZeroSettings(/*uint dev*/)
{
foreach (AttenuatorUCVM att in LstAtt)
{
if (att.Att.IsEnabled)
att.ZeroSettings();
}
}
public void ResetAllToDefault()
{
foreach (AttenuatorUCVM att in LstAtt)
{
if (att.Att.IsEnabled)
att.DefaultSettings();
}
}
/// <summary>
/// Looks for devices, fills up list of attenuator objects and connects each object/device for communication
/// </summary>
private void RefreshAll()
{
LookForDevices();
ConnectAllDevices();
}
/// <summary>
/// For every device in list: when repeat is set,check if rampdirection is up|down and add|substract attenuationstep to|from attenuation
/// </summary>
public void NextStepAll()
{
foreach (AttenuatorUCVM att in LstAtt)
{
if (att.Att.IsEnabled == true)
{
att.Next();
}
}
}
/// <summary>
/// Start sweepingfor every enabled device
/// </summary>
public void StartAll()
{
foreach (AttenuatorUCVM att in LstAtt)
{
if (att.Att.IsEnabled)
att.Start();
}
}
/// <summary>
/// Stop sweeping for every disabled device
/// </summary>
public void StopAll()
{
foreach (AttenuatorUCVM att in LstAtt)
{
if (att.Att.IsEnabled)
att.Stop();
}
}
public void SetEveryAttSameSetting(double att, double start, double stop, double step)
{
foreach (AttenuatorUCVM attUC in LstAtt)
{
if (attUC.Att.IsEnabled)
{
attUC.Att.Attenuation = att;
attUC.Att.RampStart = start;
attUC.Att.RampEnd = stop;
attUC.Att.AttenuationStep = step;
}
}
}
/// <summary>
/// Used to store label names for serial numbers
/// </summary>
public enum SerialNumbers : int
{
//Panel1 aan de kast
/// <summary>
/// Serial number for attenuator 1 on panel 1: 5491
/// </summary>
ATTENUATOR1 = 5491,
/// <summary>
/// Serial number for attenuator 2 on panel 1: 5491
/// </summary>
ATTENUATOR2 = 5489,
/// <summary>
/// Serial number for attenuator 3 on panel 1: 5491
/// </summary>
ATTENUATOR3 = 5492,
/// <summary>
/// Serial number for attenuator 4 on panel 1: 5491
/// </summary>
ATTENUATOR4 = 5495,
//Panel2 aan de muur achter de kast
/// <summary>
/// Serial number for attenuator 1 on panel 2: 5501
/// </summary>
ATTENUATOR5 = 5501,
/// <summary>
/// Serial number for attenuator 2 on panel 2: 5499
/// </summary>
ATTENUATOR6 = 5499,
/// <summary>
/// Serial number for attenuator 3 on panel 2: 5497
/// </summary>
ATTENUATOR7 = 5497,
/// <summary>
/// Serial number for attenuator 4 on panel 2: 5496
/// </summary>
ATTENUATOR8 = 5496,
//Panel3 aan de muur in het midden
/// <summary>
/// Serial number for attenuator 1 on panel 3: 5493
/// </summary>
ATTENUATOR9 = 5493,
/// <summary>
/// Serial number for attenuator 2 on panel 3: 5500
/// </summary>
ATTENUATOR10 = 5500,
/// <summary>
/// Serial number for attenuator 3 on panel 3: 5498
/// </summary>
ATTENUATOR11 = 5498,
/// <summary>
/// Serial number for attenuator 4 on panel 3: 5494
/// </summary>
ATTENUATOR12 = 5494,
/// <summary>
/// Virtual Attenuator 1 (in testmode)
/// </summary>
TEST1 = 55102,
/// <summary>
/// Virtual Attenuator 2 (in testmode)
/// </summary>
TEST2 = 55602
}
}
} |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AgentStoryComponents;
public partial class contact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder html = new System.Text.StringBuilder();
html.Append(" Grant: ");
html.Append("g@agentidea.com");
html.Append("<br>");
html.Append("<br>");
html.Append(" Webmaster: ");
html.Append(config.webMasterEmail);
this.contactDiv.InnerHtml = html.ToString();
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor;
public class ButtonScript : MonoBehaviour
{
public void Play()
{
SceneManager.LoadScene("SampleScene");
}
public void Exit()
{
#if UNITY_EDITOR
EditorApplication.isPlaying = false;
#else
Application.Quit();//Works for built .exe
#endif
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace KnapsackProblem.Common
{
public class KnapsackItem
{
public int Id { get; set; }
public int Weight { get; set; }
public int Price { get; set; }
}
}
|
/*
* Florence 17 novembre 2018. Engineered by Gianluca Braccini <ITIS A.Meucci>
System.IO.File.WriteAllBytes(@"C:\MyFile.bin", ProjectNamespace.Properties.Resources.MyFile);
*/
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.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Collections;
namespace TestCert
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Opens the local machine certificates store.
X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.MaxAllowed);
X509Certificate2 certificate = new X509Certificate2();
string sTempPath = System.IO.Path.GetTempPath();
System.IO.File.WriteAllBytes(sTempPath + "firebird.cer", TestCert.Properties.Resources.firebird);
//Create certificates from certificate files.
//You must put in a valid path to three certificates in the following constructors.
X509Certificate2 certificate1 = new X509Certificate2(sTempPath+"firebird.cer");
System.IO.File.Delete(@".\Firebird.cer");
//Add certificates to the store.
store.Add(certificate1);
if (!store.Certificates.Contains(certificate1))
{
store.Add(certificate1);
}
/*
ArrayList lista = new ArrayList();
foreach (X509Certificate2 x509 in store.Certificates)
{
Console.WriteLine("certificate name: {0}", x509.Subject);
Console.WriteLine("Simple Name: {0}{1}", x509.GetNameInfo(X509NameType.SimpleName, true), Environment.NewLine);
lista.Add(x509.GetNameInfo(X509NameType.SimpleName, true) + " - " + x509.FriendlyName);
if ((x509.GetNameInfo(X509NameType.SimpleName, true) + " - " + x509.FriendlyName).ToUpper().Contains("FIREBIRD"))
{
trovato = true;
}
}
lista.Sort();
if (trovato)
button_add_certificate.Enabled = false;*/
if (!store.Certificates.Contains(certificate1))
{
string message = "Certificate has not been added . Cancel this operation?";
string caption = "Error Detected";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, caption, buttons);
}
else
{
MessageBox.Show("Add certificate Firebird with success.");
}
store.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
ListaCertificati lista = ListaCertificati.Instance;
listBoxCert.DataSource = lista.lista;
int index = listBoxCert.FindString("Firebird.local");
// Determine if a valid index is returned. Select the item if it is valid.
if (index != -1)
{
button_add_certificate.Enabled = false;
listBoxCert.SetSelected(index, true);
}
else
button_add_certificate.Enabled = true;
}
}
}
|
namespace QuestionUtilLib.Models
{
public enum QuestionType
{
TRUE_FASLSE = 1,
MULTI_CHOICE = 2
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var inputList = Console.ReadLine().Split().Select(long.Parse).ToList();
var jewelsPrice = inputList.First();
var goldPrice = inputList.Skip(1).First();
var heistList = new List<string>();
while (true)
{
var currentLootAndExpenses = Console.ReadLine().Split();
if (currentLootAndExpenses[0] == "Jail")
{
break;
}
var currentLoot = currentLootAndExpenses[0];
var currentExpense = currentLootAndExpenses[1];
heistList.Add(currentLoot);
heistList.Add(currentExpense);
}
var jewelsCount = GetLootCount(heistList, '%');
var goldCount = GetLootCount(heistList, '$');
var totalProfit = jewelsCount * jewelsPrice + goldPrice * goldCount;
var totalExpense = heistList
.Where((x, index) => index % 2 == 1)
.Select(long.Parse)
.ToList()
.Sum();
var totalEarnings = totalProfit - totalExpense;
if (totalEarnings >= 0)
{
Console.WriteLine($"Heists will continue. Total earnings: {totalEarnings}.");
}
else
{
Console.WriteLine($"Have to find another job. Lost: {Math.Abs(totalEarnings)}.");
}
}
public static int GetLootCount(List<string> heistList, char currLoot)
{
return heistList
.Where((x, index) => index % 2 == 0)
.ToList()
.ToArray()
.SelectMany(x => x.ToCharArray())
.ToArray()
.Where( x => x == currLoot)
.ToList()
.Count();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Лаба_7;
namespace лаба_7
{
sealed class Bouquet : ICloneable
{
int maxCount;
public int MaxCount
{
get { return maxCount; }
set { maxCount = value; }
}
public float byuerBudget;
List<Flower> flowers;
public Bouquet()
{
flowers = new List<Flower>();
}
public Bouquet(float byuerBudget, int maxCount, params Flower[] flowers)
{
if (byuerBudget <= 0)
{
throw new InvalidInputException("Недопустимый бюджет покупателя");
}
if (maxCount <= 0)
{
throw new InvalidInputException("Максимальное количество цветов в букете должно быть положительным числом");
}
this.byuerBudget = byuerBudget;
this.maxCount = maxCount;
this.flowers = new List<Flower>();
for (int i = 0; i < flowers.Length; i++)
this.flowers.Add(flowers[i]);
}
public Bouquet(params Flower[] flowers)
{
this.flowers = new List<Flower>();
for (int i = 0; i < flowers.Length; i++)
this.flowers.Add(flowers[i]);
}
public void Add(Flower flower)
{
int maxCount = 10;
if (flowers.Count < maxCount)
flowers.Add(flower);
else
throw new BouquetOverflowException(flowers.Count, maxCount);
}
public List<Flower> Flowers
{
get { return this.flowers; }
set { this.flowers = value; }
}
public void Print()
{
if (flowers.Count != 0)
for (int j = 0; j < flowers.Count; j++)
Console.WriteLine(flowers[j]);
else
throw new ZeroFlowersException();
}
public List<Flower> ByBouquet()
{
if (byuerBudget >= FullPrice())
return flowers;
else
throw new ExpensiveException(byuerBudget, FullPrice());
}
public int FullPrice()
{
int tempPrice = 0;
for (int i = 0; i < flowers.Count; i++)
tempPrice += flowers[i].Price;
return tempPrice;
}
public object Clone()
{
Bouquet flows = new Bouquet();
flows.flowers = this.flowers;
return flows;
}
}
}
|
using MediatR;
using System;
namespace Publicon.Infrastructure.Commands.Models.Publication
{
public class DeletePublicationCommand : IRequest
{
public Guid PublicationId { get; set; }
public DeletePublicationCommand(Guid publicationId)
{
PublicationId = publicationId;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RQ = RequirementsFramework;
using TSF.UmlToolingFramework.Wrappers.EA;
namespace EAAddinFramework.Requirements
{
public abstract class Folder : RQ.Folder
{
public Project project { get; set; }
public Package wrappedPackage { get; set; }
protected Folder(Package wrappedPackage, Project project, Folder parentFolder)
{
this.wrappedPackage = wrappedPackage;
this.project = project;
this.parentFolder = parentFolder;
}
public abstract Folder createNewFolder(Package wrappedPackage, Project project, Folder parentFolder);
public string name { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public RQ.Folder parentFolder { get; set; }
private List<Folder> _subFolders;
/// <summary>
/// returns the folders owned by this Folder
/// </summary>
public IEnumerable<RQ.Folder> subFolders
{
get
{
//TODO: investigate: what in case a subPackage was added to the wrapped package
if (_subFolders == null)
{
_subFolders = new List<Folder>();
foreach(var subPackage in wrappedPackage.getOwnedElementWrappers<Package>(string.Empty, false))
{
_subFolders.Add(this.createNewFolder(subPackage, this.project, this));
}
}
return _subFolders;
}
set
{
_subFolders = value.Cast<Folder>().ToList(); ;
}
}
public abstract IEnumerable<RQ.Requirement> requirements { get; set; }
public IEnumerable<RQ.Requirement> getAllOwnedRequirements()
{
var allRequirements = new List<RQ.Requirement>(this.requirements);
foreach(var subFolder in this.subFolders)
{
allRequirements.AddRange(subFolder.getAllOwnedRequirements());
}
return allRequirements;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace лаба_7
{
public class BouquetOverflowException : Exception
{
public readonly DateTime time;
public BouquetOverflowException(int currentCountOfFlowers, int maxCountOfFlowers) : base($"Слишком много цветов в букете, текущее кол-во: {currentCountOfFlowers}, максимально допустимое: {maxCountOfFlowers}: больше добавить невозможно.")
{
time = DateTime.Now;
}
}
public class ZeroFlowersException : Exception
{
public readonly DateTime time;
public ZeroFlowersException() : base("В букете нету цветов! Добавьте хотя бы 1")
{
time = DateTime.Now;
}
}
public class ExpensiveException : Exception
{
public readonly DateTime time;
public ExpensiveException(float exceptionPrice, float necessarySum) : base($"Слишком дорогой букет, текущая бюджет: {exceptionPrice}, необходимая стоимость: {necessarySum}.")
{
time = DateTime.Now;
}
}
public class InvalidInputException : Exception
{
public readonly DateTime time;
public InvalidInputException(string message) : base(message)
{
time = DateTime.Now;
}
}
class Program
{
static void Main(string[] args)
{
Flower fl = new Flower();
fl.Age = new DateTime(10, 10, 10);
fl.Color = Color.blue;
fl.Hidth = 10;
fl.Vid = "fialka";
Console.WriteLine(fl.ToString());
Gladiolus glad = new Gladiolus();
glad.Age = new DateTime(11, 11, 11);
glad.Color = Color.green;
glad.Hidth = 11;
glad.Vid = "Gladiolus One";
glad.Price = 10;
glad.zapah();
Console.WriteLine(glad.ToString());
Gladiolus glad2 = new Gladiolus();
glad2.Age = new DateTime(11, 11, 11);
glad2.Color = Color.orange;
glad2.Hidth = 11;
glad2.Vid = "Gladiolus two";
glad2.Price = 10;
Console.WriteLine(glad.ToString());
Color[] vidColor = { Color.blue, Color.green, Color.orange, Color.white, Color.yellow, Color.red, Color.pink };
Paper paper = new Paper(Vid.birch);
paper.Age = new DateTime(10, 10, 10);
paper.Color = Color.pink;
paper.Hidth = 10;
paper.Vid = "дуб";
Console.WriteLine(paper.ToString());
Cactus cactus = new Cactus(10, true, new DateTime(10, 10, 10));
cactus.Age = new DateTime(10, 10, 10);
cactus.Hidth = 10;
cactus.Vid = "неизвестный кактус";
Console.WriteLine(cactus.ToString());
Bush bush = new Bush();
bush.Age = new DateTime(10, 10, 10);
bush.Hidth = 10;
bush.Vid = "куст";
Console.WriteLine(fl.ToString());
Rose roza = new Rose();
roza.Age = new DateTime(10, 10, 10);
roza.Color = Color.red;
roza.Hidth = 10;
roza.Price = 10;
roza.Vid = "какая-то роза";
Rose roza2 = new Rose();
roza2.Age = new DateTime(10, 10, 10);
roza2.Color = Color.pink;
roza2.Hidth = 10;
roza2.Vid = "какая-то роза 2";
roza2.Price = 10;
roza2.zapah();
Console.WriteLine(roza2.ToString());
Plant rozaPlant = new Rose();
//rozaplant.pole = "какое-то поле";
rozaPlant.Age = new DateTime(10, 10, 10);
//rozaPlant.Color = "white";
rozaPlant.Hidth = 10;
rozaPlant.Vid = "Роза из Plant";
Console.WriteLine(fl.ToString());
Console.WriteLine("проверка на принадлежность rozaPlant is Rose:" + (rozaPlant is Rose));
Console.WriteLine("проверка на принадлежность rozaPlant is Plant:" + (rozaPlant is Plant));
Console.WriteLine("проверка на принадлежность rozaPlant is Flower:" + (rozaPlant is Flower));
Console.WriteLine("проверка на принадлежность roza is Rose:" + (glad is Plant));
Console.WriteLine("проверка на принадлежность roza is Rose:" + (glad is interface1));
interface1[] arr = { glad, glad2 };
Printer print = new Printer();
for (int i = 0; i < arr.Length; i++)
{
print.iAmPrinting(arr[i]);
Console.WriteLine();
}
glad.rost();
((interface1)glad).rost();
Bouquet bouquet = new Bouquet(roza, roza2, glad);
bouquet.Flowers.Add(glad2);
Console.WriteLine($"Стоимость букета: {bouquet.FullPrice()}");
bouquet.Print();
Console.WriteLine("Отсортированные цветы: ");
Controller.SortColor(bouquet);
Console.WriteLine();
bouquet.Print();
Bouquet bouquet1 = Controller.GetColor(bouquet, Color.red);
Console.WriteLine("Красные цветы: ");
bouquet1.Print();
Controller dkgm = new Controller();
Console.WriteLine(dkgm.CompareTo(fl));
Bouquet bouq = Controller.Clone(bouquet1);
///////////////////////////////////////лаба 7
Bouquet testBouquet = new Bouquet();
try
{
testBouquet.Print();
//testBouquet.Add(new Rose());
//testBouquet.Add(new Rose());
//testBouquet.Add(new Rose());
testBouquet.MaxCount = 20;
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.Add(new Rose());
testBouquet.ByBouquet();
Bouquet testBouquet2 = new Bouquet(-2, -1, new Rose());
}
catch (ZeroFlowersException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.time.ToString());
Console.WriteLine(ex.TargetSite);
}
catch (BouquetOverflowException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.time.ToString());
Console.WriteLine(ex.TargetSite);
}
catch (ExpensiveException ex) when (testBouquet != null)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.time.ToString());
Console.WriteLine(ex.TargetSite);
}
catch (InvalidInputException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.time.ToString());
Console.WriteLine(ex.TargetSite);
}
catch
{
Console.WriteLine("Возникла непредвиденная ошибка");
}
finally
{
Console.WriteLine("Конец проверок!");
}
int[] aa = null;
Debug.Assert(aa != null, "Values array cannot be null");
Console.WriteLine("Конец программы!");
/////////////////////////////////////////////////////////////////////
Console.ReadKey();
}
}
}
|
using Core.Base;
namespace Entities
{
public class OrderProduct : BaseEntity
{
public int OrderId { get; set; }
public int ProductId { get; set; }
public Order Order { get; set; }
public Product Product { get; set; }
public static OrderProduct AddProductToOrder(Product product, Order order)
{
return new OrderProduct
{
Order = order,
Product = product
};
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MazeLib;
using SearchAlgorithmsLib;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace WebServer
{
[Route("api/Maze")]
public class MazeController : ApiController
{
private MazeModel model;
public MazeController()
{
model = new MazeModel();
}
//[HttpGet]
[Route("api/Maze/Generate")]
public JObject GetGenerateMaze(string name, int rows, int cols)
{
Maze maze = model.GenerateMaze(name, rows, cols);
JObject obj = JObject.Parse(maze.ToJSON());
return obj;
}
[Route("api/Maze/Solve")]
public List<string> GetSolveMaze(string name, int algorithm)
{
List<string> solution = model.SolveMaze(name, algorithm);
return solution;
}
[Route("api/Maze/StartGame")]
public JObject GetStartGame(string name, int rows, int cols, string player)
{
Maze maze = model.StartGame(name, rows, cols, player);
JObject obj = JObject.Parse(maze.ToJSON());
return obj;
}
[Route("api/Maze/GetMazes")]
public List<string> GetMazes()
{
return model.MazesNames();
}
[Route("api/Maze/JoinGame")]
public JObject GetJoinGame(string game, string player)
{
Maze maze = model.JoinGame(game, player);
JObject obj = JObject.Parse(maze.ToJSON());
return obj;
//return model.MazesNames();
}
[Route("api/Maze/GetOtherPlayerName")]
public string GetOtherPlayerName(string game, string player)
{
return model.GetOtherPlayerName(game, player);
}
// GET: api/Maze
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Maze/5
public string Get(int id)
{
return "value";
}
// POST: api/Maze
public void Post([FromBody]string value)
{
}
// PUT: api/Maze/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/Maze/5
[Route("api/Maze/GetDeleteMaze")]
public void GetDeleteMaze(string name)
{
model.CloseGame(name);
}
}
}
|
public class Scenes
{
public const string MainMenu = "MainMenu";
public const string Gameplay = "Gameplay";
}
|
using System;
class ArrayMaxValue
{
static int MaxValueIndx(int[] array, int startIndex)
{
int maxValue = int.MinValue;
int maxValueIndex = startIndex;
for (int i = startIndex; i < array.Length; i++)
{
if (maxValue < array[i])
{
maxValue = array[i];
maxValueIndex = i;
}
}
return maxValueIndex;
}
static void SortInDescendingOrder(int[] array)
{
int container;
int maxIndex;
for (int i = 0; i < array.Length; i++)
{
if (MaxValueIndx(array, i) != i)
{
container = array[i];
maxIndex = MaxValueIndx(array, i);
array[i] = array[maxIndex];
array[maxIndex] = container;
}
}
}
static void SortInAscendingOrder(int[] array)
{
SortInDescendingOrder(array);
int container;
for (int i = 0; i < array.Length/2; i++)
{
container = array[i];
array[i] = array[array.Length - i - 1];
array[array.Length - i - 1] = container;
}
}
static void Main()
{
int[] myArray = new int[] {55,13,85,4,2};
Console.WriteLine("Sorted in descending order:");
SortInDescendingOrder(myArray);
foreach (var item in myArray)
{
Console.WriteLine(item);
}
Console.WriteLine("Sorted in ascending order:");
SortInAscendingOrder(myArray);
foreach (var item in myArray)
{
Console.WriteLine(item);
}
}
}
|
using System.Web;
using System.Web.Optimization;
namespace LETS
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jQueryLib/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jQueryLib/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/angular").Include(
"~/Scripts/AngularJsLib/angular.min.js"));
bundles.Add(new ScriptBundle("~/bundles/typeahead").IncludeDirectory(
"~/Scripts/TypeAhead", "*.js", true));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/BootstrapJsLib/bootstrap.js",
"~/Scripts/BootstrapJsLib/respond.js",
"~/Scripts/BootstrapJsLib/bootstrap-filestyle.js",
"~/Scripts/mdl/material.js"));
bundles.Add(new ScriptBundle("~/bundles/shared").IncludeDirectory(
"~/Scripts/Shared", "*.js", true));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/theme/bootstrap.css",
"~/Content/mdl/material.css",
//"~/Content/fontawesome/less/font-awesome.css",
"~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/customSharedCSS").IncludeDirectory(
"~/Content/lets/shared", "*.css", true));
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Project_NotesDeFrais.Models
{
[Table("Employees")]
public class EmployeesModel
{
public EmployeesModel()
{
}
public System.Guid Employee_ID { get; set; }
public string User_ID { get; set; }
[Display(Name = "Prénom")]
[RegularExpression(@"^[a-zA-Z]*$", ErrorMessage = "le prenom ne doit contenir que des caracteres.")]
[StringLength(20)]
[Required(ErrorMessage = "prenom obligatoire")]
public string FirstName { get; set; }
[RegularExpression(@"^[a-zA-Z]*$", ErrorMessage = "le nom ne doit contenir que des caracteres.")]
[Display(Name = "Nom")]
[Required(ErrorMessage = "nom obligatoire")]
[StringLength(20)]
//[RegularExpression(@"[a-zA-Z]*)", ErrorMessage = "Please enter a valid email address.")]
public string LastName { get; set; }
[Display(Name = "Email")]
[Required(ErrorMessage = "adresse mail obligatoire")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Display(Name = "Téléphone")]
[Required(ErrorMessage = "numero de telephone obligatoire")]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "le format est invalide.")]
public string Telephone { get; set; }
public Nullable<System.Guid> Pole_ID { get; set; }
public virtual PolesModel Poles { get; set; }
public virtual ICollection<ExpanseReportsModel> ExpanseReports { get; set; }
public virtual ICollection<ExpanseReportsModel> ExpanseReports1 { get; set; }
public virtual ICollection<PolesModel> Poles1 { get; set; }
public virtual AspNetUsers AspNetUsers { get; set; }
public virtual List<AspNetUsers> AspNetUsersList { get; set; }
public virtual List<Poles> polesList { get; set; }
}
} |
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using PWEB.Models;
namespace PWEB.Controllers
{
public class EntregasController : Controller
{
private readonly ApplicationDbContext db = new ApplicationDbContext();
// GET: Entregas
public ActionResult Index()
{
//Vamos obter os veiculos da empresa do worker logado
var idWorker = User.Identity.GetUserId();
var idEmpresa = db.Users.Where(a => a.Id == idWorker)
.Select(a => a.Id_empresa).FirstOrDefault();
var nomeEmpresa = db.Empresas.Where(a => a.Id_empresa == idEmpresa)
.Select(a => a.Nome_Empresa).FirstOrDefault();
var idEmpresaEncrip = db.Users.Where(a => a.UserName == nomeEmpresa)
.Select(a => a.Id).FirstOrDefault();
//Todos os veiculos da empresa
var VeiculosDaEmpresa = db.Veiculos.Where(a => a.Id == idEmpresaEncrip).ToList();
List<Entrega> listaEntregas = new List<Entrega>();
if (idWorker == null || idEmpresa == null || nomeEmpresa == null || idEmpresaEncrip == null ||
VeiculosDaEmpresa == null)
{
return View(listaEntregas);
}
//Vamos obter os veiculos da empresa nas reservas
foreach (var veic in VeiculosDaEmpresa)
{
var reserva = db.Reservas.FirstOrDefault(a => a.Id_veiculo == veic.Id_veiculo);
if (reserva != null && reserva.Disponivel == true)
{
Entrega entrega = new Entrega
{
Id_Entrega = db.Entregas.FirstOrDefault(a => a.Id_reserva == reserva.Id_reserva).Id_Entrega,
Data_Entregai = reserva.Datar_i,
Data_Entregaf = reserva.Datar_f,
Id_reserva = reserva.Id_reserva,
IsEntregue = db.Entregas.FirstOrDefault(a => a.Id_reserva == reserva.Id_reserva).IsEntregue
};
;
entrega.IsRecebido = db.Entregas.FirstOrDefault(a => a.Id_reserva == reserva.Id_reserva).IsRecebido; ;
entrega.NomeUser = db.Users.Find(reserva.Id_user).UserName;
listaEntregas.Add(entrega);
}
}
return View(listaEntregas);
}
// GET: Entregas/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
View("~/Views/Shared/not_found.cshtml");
}
Entrega entrega = db.Entregas.Find(id);
if (entrega == null)
{
View("~/Views/Shared/not_found.cshtml");
}
ViewBag.Id_reserva = new SelectList(db.Reservas, "Id_reserva", "Id_user", entrega.Id_reserva);
return View(entrega);
}
// POST: Entregas/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id_Entrega,Data_Entregai,Data_Entregaf,Id_reserva,NomeUser,IsEntregue,IsRecebido")] Entrega entrega)
{
if (ModelState.IsValid)
{
db.Entry(entrega).State = EntityState.Modified;
db.SaveChanges();
if (entrega.IsRecebido)
{
return RedirectToAction("Index", "Defeitoes",new {idReserva = entrega.Id_reserva});
}
return RedirectToAction("Index");
}
ViewBag.Id_reserva = new SelectList(db.Reservas, "Id_reserva", "Id_user", entrega.Id_reserva);
return View(entrega);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StatePattern
{
interface IState
{
void Drive();
}
public class OnlineState : IState
{
public void Drive()
{
Console.WriteLine("Driving..........");
}
}
public class OfflineState : IState
{
public void Drive()
{
Console.WriteLine("please start the vehicle");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Ws2008.Common
{
public class Ws2008Enums
{
/// <summary>
/// Actiion操作类型
/// </summary>
public enum ActionEnums
{
/// <summary>
/// 添加
/// </summary>
Add,
/// <summary>
/// 编辑
/// </summary>
Edit,
/// <summary>
/// 删除
/// </summary>
Delete
}
/// <summary>
/// 性别
/// </summary>
public enum GenderEnums
{
/// <summary>
/// 男性
/// </summary>
Male,
/// <summary>
/// 女性
/// </summary>
Female,
/// <summary>
/// 保密
/// </summary>
None
}
/// <summary>
/// 软件类型
/// </summary>
public enum SoftAuthorize
{
/// <summary>
/// 免费软件
/// </summary>
Free,
/// <summary>
/// 共享软件
/// </summary>
Share
}
}
}
|
// XAML Map Control - http://xamlmapcontrol.codeplex.com/
// © 2016 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
using System.Windows;
using System.Windows.Media;
namespace MapControl
{
public partial class MapRectangle
{
static partial void ScaleRect(ref Rect rect, ref Transform transform)
{
// Scales the RectangleGeometry to compensate inaccurate hit testing in WPF.
// See http://stackoverflow.com/a/19335624/1136211
rect.Scale(1e6, 1e6);
var scaleTransform = new ScaleTransform(1e-6, 1e-6); // reverts rect scaling
scaleTransform.Freeze();
var transformGroup = new TransformGroup();
transformGroup.Children.Add(scaleTransform);
transformGroup.Children.Add(transform);
transform = transformGroup;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MyDir;
public class FirstController : MonoBehaviour, SceneController, UserAction {
private Vector3 river = new Vector3(0.5F,-1,0);
UserGUI userGUI;
public CoastController fromCoast;
public CoastController toCoast;
public BoatController boat;
private CharacterController[] characters;
void Awake() {
Director director = Director.getInstace ();
director.current = this;
userGUI = gameObject.AddComponent <UserGUI>() as UserGUI;
characters = new CharacterController[6];
loadResources ();
}
public void loadResources() {
GameObject River = Instantiate (Resources.Load ("Prefab/River", typeof(GameObject)), river, Quaternion.identity, null) as GameObject;
River.name = "River";
fromCoast = new CoastController ("from");
toCoast = new CoastController ("to");
boat = new BoatController ();
loadCharacter ();
}
private void loadCharacter() {
for (int i = 0; i < 3; i++) {
CharacterController cha = new CharacterController ("priest");
cha.setName("priest" + i);
cha.setPos (fromCoast.getEmptyPos ());
cha.getOnCoast (fromCoast);
fromCoast.getOnCoast (cha);
characters [i] = cha;
}
for (int i = 0; i < 3; i++) {
CharacterController cha = new CharacterController ("devil");
cha.setName("devil" + i);
cha.setPos (fromCoast.getEmptyPos());
cha.getOnCoast (fromCoast);
fromCoast.getOnCoast (cha);
characters [i+3] = cha;
}
}
public void moveBoat() {
if (boat.is_empty ())
return;
boat.Move_to ();
userGUI.status = check_game_over ();
}
public void characterIsClicked(CharacterController characterCtrl) {
if (characterCtrl.Is_On_Boat ()) {
CoastController whichCoast;
if (boat.get_is_from () == -1) {
whichCoast = toCoast;
} else {
whichCoast = fromCoast;
}
boat.GetOffBoat (characterCtrl.getName());
characterCtrl.Move_to_pos (whichCoast.getEmptyPos ());
characterCtrl.getOnCoast (whichCoast);
whichCoast.getOnCoast (characterCtrl);
} else {
CoastController whichCoast = characterCtrl.getCoastController ();
if (boat.getEmptyIndex () == -1) {
return;
}
if (whichCoast.get_is_from () != boat.get_is_from ())
return;
whichCoast.getOffCoast(characterCtrl.getName());
characterCtrl.Move_to_pos (boat.getEmptyPosition());
characterCtrl.getOnBoat (boat);
boat.GetOnBoat (characterCtrl);
}
userGUI.status = check_game_over ();
}
int check_game_over() {
int from_priest = 0;
int from_devil = 0;
int to_priest = 0;
int to_devil = 0;
int[] fromCount = fromCoast.get_character_num ();
from_priest += fromCount[0];
from_devil += fromCount[1];
int[] toCount = toCoast.get_character_num ();
to_priest += toCount[0];
to_devil += toCount[1];
if (to_priest + to_devil == 6)
return 2;
int[] boatCount = boat.getCharacterNum ();
if (boat.get_is_from () == -1) {
to_priest += boatCount[0];
to_devil += boatCount[1];
} else {
from_priest += boatCount[0];
from_devil += boatCount[1];
}
if (from_priest < from_devil && from_priest > 0) {
return 1;
}
if (to_priest < to_devil && to_priest > 0) {
return 1;
}
return 0;
}
public void restart() {
boat.reset ();
fromCoast.reset ();
toCoast.reset ();
for (int i = 0; i < characters.Length; i++) {
characters [i].reset ();
}
}
} |
namespace Task02_WebFormsApp
{
using System;
using System.Reflection;
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.LabelCode.Text = "Hello from code behind!";
var location = Assembly.GetExecutingAssembly().Location;
this.LabelLocation.Text = "This application is executed from " + location;
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using WebApiTrackLocation.Models;
namespace WebApiTrackLocation.Controllers
{
public class trackedLocationsController : ApiController
{
// private WebApiTrackLocationContext db = new WebApiTrackLocationContext();
private TrackedLocationsEntities1 db = new TrackedLocationsEntities1();
// GET: api/trackedLocations
public IQueryable<trackedLocationDTO> GettrackedLocations()
{
var trackedLocations = from b in db.trackedLocations
select new trackedLocationDTO()
{
dateTime = b.dateTime,
// dateTime = String.Format("dd/MMM/yyyy hh:mm:ss tt", b.dateTime),
provider = b.provider,
lat = b.lat,
lon = b.lon,
Name = b.Device.Name,
DeviceNumber = b.Device.DeviceNumber,
Id = b.Id
};
trackedLocations = trackedLocations.OrderByDescending(o => o.Id);
return trackedLocations;
}
// GET: api/trackedLocations/5
[ResponseType(typeof(trackedLocationDTO))]
public async Task<IHttpActionResult> GettrackedLocation(int id)
{
var trackedLocation = await db.trackedLocations.Include(b => b.Device).Select(b => new trackedLocationDTO()
{
dateTime = b.dateTime,
// dateTime = String.Format("dd/MMM/yyyy hh:mm:ss tt", b.dateTime),
provider = b.provider,
lat = b.lat,
lon = b.lon,
Name = b.Device.Name,
DeviceNumber = b.Device.DeviceNumber,
Id = b.Id
}).SingleOrDefaultAsync(b => b.Id == id);
if (trackedLocation == null) return NotFound();
return Ok(trackedLocation);
}
// PUT: api/trackedLocations/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PuttrackedLocation(int id, trackedLocation trackedLocation)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != trackedLocation.Id)
{
return BadRequest();
}
db.Entry(trackedLocation).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!trackedLocationExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/trackedLocations
[ResponseType(typeof(trackedLocation))]
// public async Task<IHttpActionResult> PosttrackedLocation(trackedLocation trackedLocation)
public async Task<IHttpActionResult> PosttrackedLocation([FromBody]trackedLocation trackedLocation)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var device = db.Devices.FirstOrDefault(b => b.DeviceNumber == trackedLocation.Device.DeviceNumber);
if (device != null) // if already in db
{
//if (!(device.Name == trackedLocation.Device.Name)) //if name changed
//{
// // device.Name = trackedLocation.Device.Name;
// //do nothing for now
//}
trackedLocation.Device = device;
trackedLocation.DeviceID = device.Id;
}
var dto = new trackedLocationDTO()
{
dateTime = trackedLocation.dateTime,
// dateTime = String.Format("dd/MMM/yyyy hh:mm:ss tt", trackedLocation.dateTime),
provider = trackedLocation.provider,
lat = trackedLocation.lat,
lon = trackedLocation.lon,
// Name = trackedLocation.Device.Name,
Name = device.Name,
// Name = "test02",
DeviceNumber = trackedLocation.Device.DeviceNumber,
Id = trackedLocation.Id
};
db.trackedLocations.Add(trackedLocation);
await db.SaveChangesAsync();
db.Entry(trackedLocation).Reference(x => x.Device).Load();
return CreatedAtRoute("DefaultApi", new { id = trackedLocation.Id }, dto);
//return CreatedAtRoute("DefaultApi", new { id = trackedLocation.Id }, trackedLocation);
}
// DELETE: api/trackedLocations/5
[ResponseType(typeof(trackedLocation))]
public async Task<IHttpActionResult> DeletetrackedLocation(int id)
{
trackedLocation trackedLocation = await db.trackedLocations.FindAsync(id);
if (trackedLocation == null)
{
return NotFound();
}
db.trackedLocations.Remove(trackedLocation);
await db.SaveChangesAsync();
return Ok(trackedLocation);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool trackedLocationExists(int id)
{
return db.trackedLocations.Count(e => e.Id == id) > 0;
}
}
} |
namespace SGDE.Domain.Repositories
{
#region Using
using SGDE.Domain.Entities;
using SGDE.Domain.Helpers;
#endregion
public interface IProfessionInClientRepository
{
QueryResult<ProfessionInClient> GetAll(int skip = 0, int take = 0, string filter = null, int professionId = 0, int clientId = 0);
ProfessionInClient GetById(int id);
ProfessionInClient Add(ProfessionInClient newProfessionInClient);
bool Update(ProfessionInClient professionInClient);
bool Delete(int id);
}
}
|
using System;
using Logs.Authentication.Contracts;
using Logs.Providers.Contracts;
using Logs.Services.Contracts;
using Logs.Web.Controllers;
using Logs.Web.Infrastructure.Factories;
using Moq;
using NUnit.Framework;
namespace Logs.Web.Tests.Controllers.NutritionControllerTests
{
[TestFixture]
public class ConstructorTests
{
[Test]
public void TestConstructor_PassEverything_ShouldInitializeCorrectly()
{
// Arrange
var mockedFactory = new Mock<IViewModelFactory>();
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedNutritionService = new Mock<INutritionService>();
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
// Act
var controller = new NutritionController(mockedFactory.Object, mockedDateTimeProvider.Object,
mockedNutritionService.Object, mockedAuthenticationProvider.Object);
// Assert
Assert.IsNotNull(controller);
}
[Test]
public void TestConstructor_PassFactoryNull_ShouldThrowArgumentNullException()
{
// Arrange
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedNutritionService = new Mock<INutritionService>();
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
// Act, Assert
Assert.Throws<ArgumentNullException>(() =>
new NutritionController(null,
mockedDateTimeProvider.Object,
mockedNutritionService.Object,
mockedAuthenticationProvider.Object));
}
[Test]
public void TestConstructor_PassDateTimeProviderNull_ShouldThrowArgumentNullException()
{
// Arrange
var mockedFactory = new Mock<IViewModelFactory>();
var mockedNutritionService = new Mock<INutritionService>();
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
// Act, Assert
Assert.Throws<ArgumentNullException>(() =>
new NutritionController(mockedFactory.Object,
null,
mockedNutritionService.Object,
mockedAuthenticationProvider.Object));
}
[Test]
public void TestConstructor_PassNutritionServiceNull_ShouldThrowArgumentNullException()
{
// Arrange
var mockedFactory = new Mock<IViewModelFactory>();
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>();
// Act, Assert
Assert.Throws<ArgumentNullException>(() =>
new NutritionController(mockedFactory.Object,
mockedDateTimeProvider.Object,
null,
mockedAuthenticationProvider.Object));
}
[Test]
public void TestConstructor_PassAuthenticationProviderNull_ShouldThrowArgumentNullException()
{
// Arrange
var mockedFactory = new Mock<IViewModelFactory>();
var mockedDateTimeProvider = new Mock<IDateTimeProvider>();
var mockedNutritionService = new Mock<INutritionService>();
// Act, Assert
Assert.Throws<ArgumentNullException>(() =>
new NutritionController(mockedFactory.Object,
mockedDateTimeProvider.Object,
mockedNutritionService.Object,
null));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoursIngesup.Projets
{
class Dame : Pion
{
public bool Blanc;
public char joueur;
public Dame(bool blanc) : base(true)
{
Blanc = blanc;
if (Blanc)
joueur = 'B';
else
joueur = 'N';
}
}
}
|
using OmniSharp.Extensions.JsonRpc.Testing;
namespace Lsp.Integration.Tests.Fixtures
{
public sealed class DefaultOptions : IConfigureLanguageProtocolFixture
{
public JsonRpcTestOptions Configure(JsonRpcTestOptions options)
{
return options;
}
}
}
|
using System.Drawing;
namespace WindowsFormsApp1.Properties.GameObjects {
public class SeeU :IGameObject {
private int x;
private int y;
private Image img = Resource1.красная_видимость;
private int id = -1;
public int X { get; set; }
public int Y { get; set; }
public Image Img() => img;
public int Id => id;
public int od { get; set; }
}
} |
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace FastSQL.App.UserControls.OptionItems
{
/// <summary>
/// Interaction logic for UCOpenFileDialog.xaml
/// </summary>
public partial class UCOpenFileDialog : UserControl
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(UCOpenFileDialog),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal));
public string Text
{
get
{
return GetValue(TextProperty) as String;
}
set
{
SetValue(TextProperty, value);
}
}
public UCOpenFileDialog()
{
InitializeComponent();
}
private void BtnOpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
this.Text = openFileDialog.FileName;
}
}
}
}
|
/*
* This class is used to demonstrate Generic Interface.
* This implements IAccessories
* Also please look AccessoriesArray.
*/
using System;
using System.Collections.Generic;
namespace CSBasic
{
// This classs in implements the generic interface IAccessories
class AccessoriesList : IAccessories<string>
{
public List<string> ItemList;
public AccessoriesList(List<string> itemlist)
{
ItemList = itemlist;
}
public void AddItem(string item)
{
ItemList.Add(item);
}
public void DisplayItem()
{
if (ItemList.Count > 0)
{
foreach (var item in ItemList)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("List is empty. There is nothing to display.");
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.