text
stringlengths 13
6.01M
|
|---|
using System;
using SQLite;
using FuelRadar.Model;
namespace FuelRadar.Data
{
/// <summary>
/// The favourite gas station data structure for the database
/// </summary>
[Table(DbConstants.FavoriteStationsTable)]
public class FavouriteStationData
{
[Column(DbConstants.FavoriteStations.Id), Unique]
public String ID { get; set; }
[Column(DbConstants.FavoriteStations.Name)]
public String Name { get; set; }
[Column(DbConstants.FavoriteStations.Brand)]
public int Brand { get; set; }
[Column(DbConstants.FavoriteStations.Latitude)]
public double Latitude { get; set; }
[Column(DbConstants.FavoriteStations.Longitude)]
public double Longitude { get; set; }
public FavouriteStationData()
{
}
public FavouriteStationData(Station station)
{
this.ID = station.ID;
this.Name = station.Name;
this.Brand = (int)station.Brand;
this.Latitude = station.Location.Latitude;
this.Longitude = station.Location.Longitude;
}
public Station ToStation()
{
return new Station(this.ID, this.Name, this.Brand, this.Latitude, this.Longitude);
}
}
}
|
using BenefitDeduction.Employees.FamilyMembers;
using System.Collections.Generic;
namespace BenefitDeduction.Employees.Exempts
{
public interface IEmployeeExemptRepository: IEmployeeRepository
{
}
}
|
using AutoMapper;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using TimeTableApi.Application.Shared.EventManagement;
using TimeTableApi.Application.Shared.EventManagement.Dtos;
using TimeTableApi.Application.Shared.RoleManagement;
using TimeTableApi.Application.Shared.RoleManagement.Dtos;
using TimeTableApi.Application.Shared.UserManagement;
using TimeTableApi.Application.Shared.UserManagement.Dtos;
using TimeTableApi.Core.Entities;
using TimeTableApi.DB.Models;
namespace TimeTableApi.Application.RoleManagement
{
public class RoleAppService : IRoleAppService
{
private readonly IMongoCollection<Role> _roles;
private readonly IMapper _mapper;
public RoleAppService(
IDatabaseSettings settings,
IMapper mapper
)
{
_mapper = mapper;
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_roles = database.GetCollection<Role>("Roles");
}
public void CreateOrUpdate(CreateOrEditRoleInputDto input)
{
if (string.IsNullOrEmpty(input.Id))
{
Create(input);
}
else
{
Update(input);
}
}
private void Create(CreateOrEditRoleInputDto input)
{
var role = _mapper.Map<Role>(input);
_roles.InsertOne(role);
}
private void Update(CreateOrEditRoleInputDto input)
{
var role = _mapper.Map<Role>(input);
_roles.ReplaceOne(x=> x.Id == role.Id, role);
}
public void Remove(string id)
{
_roles.DeleteOne(x => x.Id == id);
}
public List<RoleDto> GetAll()
{
var roles = _roles.Find(role => true).ToList();
return _mapper.Map<List<RoleDto>>(roles);
}
public RoleDto GetById(string id)
{
var role = _roles.Find(x=> x.Id == id).FirstOrDefault();
return _mapper.Map<RoleDto>(role);
}
public RoleDto GetByName(string name)
{
var role = _roles.Find(x => x.Name == name).FirstOrDefault();
return _mapper.Map<RoleDto>(role);
}
}
}
|
using System;
namespace TsFromCsGenerator.Tests.Content
{
public class MultipleClasses1Model
{
public string StringProp { get; set; }
}
public class MultipleClasses2Model
{
public string StringProp { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lab9.Models;
using Lab9.DataAbstractionLayer;
namespace Lab9.Controllers
{
public class EditBookController : Controller
{
// GET: EditBook
public ActionResult Index(int id)
{
return View("EditBook");
}
public string DeleteBook()
{
int id =Int32.Parse(Request.Params["id"]);
DAL dal = new DAL();
bool result = dal.deleteBook(id);
if (result)
return "Book was successfully deleted";
else
return "Book coudln't be deleted";
}
public string UpdateBook()
{
int id = Int32.Parse(Request.Params["id"]);
int pages = Int32.Parse(Request.Params["pages"]);
string genre = Request.Params["genre"];
string lended = Request.Params["lended"];
DAL dal = new DAL();
bool result = dal.updateBook(id, pages, genre, lended);
if (result)
return "Book was successfully updated";
else
return "Book coudln't be updated";
}
public ActionResult GetOneBook()
{
int id = Int32.Parse(Request.Params["id"]);
DAL dal = new DAL();
Book book = dal.getOneBook(id);
return Json(new { book = book }, JsonRequestBehavior.AllowGet);
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using URl_Project.Interfaces;
using URl_Project.Models;
namespace URl_Project.Repositories
{
public class EFUnitOfWork : IUnitOfWork
{
private readonly UrlContext db;
private UrlModelRepository urlModelRepository;
private ILoggerFactory loggerFactory;
public EFUnitOfWork(DbContextOptions<UrlContext> options, ILoggerFactory loggerFactory)
{
db = new UrlContext(options);
this.loggerFactory = loggerFactory;
}
public IRepository<UrlModel> UrlModels
{
get
{
if (urlModelRepository == null)
{
urlModelRepository = new UrlModelRepository(db, loggerFactory);
}
return urlModelRepository;
}
}
private bool disposed = false;
public virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
db.Dispose();
}
this.disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Save()
{
db.SaveChanges();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResourcePile : MonoBehaviour {
public GameObject explosion;
public float totalMinerals = 10000;
public float curMinerals { get; private set; }
public float bucketBarYPosition = 20.0F;
private StatusBar bucketBar;
private bool isSelected = false;
// Use this for initialization
void Start () {
bucketBar = new StatusBar (gameObject, bucketBarYPosition * -1, Color.blue, Color.yellow);
curMinerals = totalMinerals;
}
/// <summary>
/// Pull minerals from the asteroid, once the asteroid is depleted it will be destroyed
/// </summary>
/// <param name="mineralsToPull">Minerals to pull.</param>
public void PullMinerals(float mineralsToPull)
{
curMinerals -= mineralsToPull;
if (curMinerals <= 0) {
Instantiate (explosion, transform.position, transform.rotation);
Destroy (gameObject);
}
float bucketPercent = curMinerals * 100 / totalMinerals;
bucketBar.UpdateStatus (bucketPercent);
}
/// <summary>
/// Select the asteroid for the purpose of displaying the avilable minerals remaining
/// </summary>
public void SelectUnit()
{
isSelected = true;
}
/// <summary>
/// Deselects the asteroid no longer showing mineral information.
/// </summary>
public void DeselectUnit()
{
isSelected = false;
}
/// <summary>
/// Display the status of the asteroid
/// </summary>
void OnGUI()
{
if (isSelected) {
bucketBar.Display ();
}
}
}
|
using System;
using UnityEngine.Events;
using UnityAtoms.SceneMgmt;
namespace UnityAtoms.SceneMgmt
{
/// <summary>
/// None generic Unity Event of type `SceneField`. Inherits from `UnityEvent<SceneField>`.
/// </summary>
[Serializable]
public sealed class SceneFieldUnityEvent : UnityEvent<SceneField> { }
}
|
using Microsoft.Practices.ServiceLocation;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using SpatialEye.Framework.Authentication;
using SpatialEye.Framework.Client;
using SpatialEye.Framework.Features;
using SpatialEye.Framework.Features.Services;
using SpatialEye.Framework.Features.Expressions;
using SpatialEye.Framework.Parameters;
using SpatialEye.Framework.Queries;
using SpatialEye.Framework.ServiceProviders;
using Lite.Resources.Localization;
using SpatialEye.Framework.Queries.Services;
namespace Lite
{
/// <summary>
/// The viewModel that handles multiple queries; some coming from the server(s) and
/// some that are set up client-side. All are specific implementations of LiteQueryViewModel.
/// </summary>
public class LiteQueriesViewModel : ViewModelBase
{
#region Property Names
/// <summary>
/// The queries that are being handled
/// </summary>
public const string QueriesPropertyName = "Queries";
/// <summary>
/// A flag indicating whether the queriesViewModel is busy
/// </summary>
public const string IsBusyPropertyName = "IsBusy";
/// <summary>
/// The New User Query that is being set up
/// </summary>
public const string NewQueryPropertyName = "NewQuery";
/// <summary>
/// The new Query ViewModel for interaction with the new query
/// </summary>
public const string NewQueryViewModelPropertyName = "NewQueryViewModel";
/// <summary>
/// The view visibility of the new query
/// </summary>
public const string NewQueryViewVisibilityPropertyName = "NewQueryViewVisibility";
/// <summary>
/// The custom queries visibility
/// </summary>
public const string CustomQueriesVisibilityPropertyName = "CustomQueriesVisibility";
#endregion
#region Fields
/// <summary>
/// The queries that are presented to the user
/// </summary>
private SortedObservableCollection<LiteQueryViewModel> _queries;
/// <summary>
/// The query filter, indicating which queries are allowed
/// </summary>
private Predicate<FeatureCollectionQueryDefinition> _queryDefinitionFilter;
/// <summary>
/// A flag indicating whether the queries viewBodel is busy
/// </summary>
private bool _isBusy;
/// <summary>
/// The viewModel that handles the UI for setting up a new Client Query
/// </summary>
private LiteNewUserQueryViewModel _newQueryViewModel;
/// <summary>
/// The resulting new clientQuery ViewModel
/// </summary>
private LiteQueryViewModel _newQuery;
/// <summary>
/// The visibility of the new QueryView
/// </summary>
private Visibility _newQueryViewVisibility;
/// <summary>
/// Do we allow custom queries
/// </summary>
private bool _isCustomQueriesVisible = true;
#endregion
#region Constructor
/// <summary>
/// The constructor
/// </summary>
/// <param name="messenger"></param>
public LiteQueriesViewModel(Messenger messenger = null)
: base(messenger)
{
Resources = new Lite.Resources.Localization.ApplicationResources();
NewQueryViewModel = new LiteNewUserQueryViewModel(messenger);
_newQueryViewVisibility = Visibility.Collapsed;
SetupCommands();
AttachToMessengerAndParameters();
}
#endregion
#region Messenger and Parameter handling
/// <summary>
/// Attach to messenger and the parameters
/// </summary>
private void AttachToMessengerAndParameters()
{
if (!IsInDesignMode)
{
this.Messenger.Register<LiteActionRunningStateMessage>(this, HandleRunningStateChange);
SystemParameterManager.Instance.ParameterValueChanged += HandleSystemParameterValueChanged;
}
}
/// <summary>
/// Handles the change in running state
/// </summary>
private void HandleRunningStateChange(LiteActionRunningStateMessage runningStateMessage)
{
// Propagate the changes to the individual queries; in case one of the queries
// is responsible for the running-state change, make it display the progress indicator.
foreach (var query in this.Queries)
{
query.HandleRunningStateChange(runningStateMessage);
}
if (this.NewQuery != null)
{
this.NewQuery.HandleRunningStateChange(runningStateMessage);
}
}
/// <summary>
/// Callback for changes in system parameters; request all queries to have their state checked
/// </summary>
void HandleSystemParameterValueChanged(ParameterDefinition definition, ParameterValue sender)
{
CheckCommands();
}
#endregion
#region Commands
/// <summary>
/// The command that should open the selected query
/// This controls the QueryDialogViewVisibility
/// /// </summary>
public RelayCommand OpenNewQueryDialogCommand { get; set; }
/// <summary>
/// The command that should close the active query.
/// This controls the QueryDialogViewVisibility
/// </summary>
public RelayCommand CloseNewQueryDialogCommand { get; set; }
/// <summary>
/// The command that should close the active query.
/// This controls the QueryDialogViewVisibility
/// </summary>
public RelayCommand SaveNewQueryCommand { get; set; }
/// <summary>
/// The command that should close the active query.
/// This controls the QueryDialogViewVisibility
/// </summary>
public RelayCommand RunNewQueryCommand { get; set; }
/// <summary>
/// Set up the available commands of the view model
/// </summary>
private void SetupCommands()
{
// Set up the open/close commands using lambdas
OpenNewQueryDialogCommand = new RelayCommand(
() =>
{
NewQueryViewModel.ResetNewQueryName();
NewQueryViewVisibility = Visibility.Visible;
},
() => this.NewQueryViewVisibility == Visibility.Collapsed);
CloseNewQueryDialogCommand = new RelayCommand(() => NewQueryViewVisibility = Visibility.Collapsed, () => NewQueryViewVisibility == Visibility.Visible);
// Set up the save command using a separate method for carrying out the actual saving of the new query
RunNewQueryCommand = new RelayCommand(RunNewQuery, () => NewQueryViewVisibility == Visibility.Visible);
SaveNewQueryCommand = new RelayCommand(SaveNewQuery, () => NewQueryViewVisibility == Visibility.Visible);
}
/// <summary>
/// Check the enabled states of the commands
/// </summary>
private void CheckCommands()
{
OpenNewQueryDialogCommand.RaiseCanExecuteChanged();
RunNewQueryCommand.RaiseCanExecuteChanged();
SaveNewQueryCommand.RaiseCanExecuteChanged();
CloseNewQueryDialogCommand.RaiseCanExecuteChanged();
}
/// <summary>
/// Returns a new external name for the specified suggested name
/// </summary>
private string UniqueExternalNameFor(string suggestedExternalName)
{
var externalName = suggestedExternalName;
var exists = new Func<string, bool>(n => Queries.Where(m => m.ExternalName.ToLower().Equals(n)).Count() > 0);
int count = 2;
while (exists(externalName.ToLower())) externalName = externalName = string.Format("{0} ({1})", suggestedExternalName, count++);
return externalName;
}
/// <summary>
/// The method that handles running the new query
/// </summary>
private void RunNewQuery()
{
var mode = this.NewQueryViewModel.SelectedMode;
if (mode != null)
{
// Get new Query details from the selected mode
var table = mode.TableDescriptor;
var expression = mode.NewQueryExpression();
var parameters = mode.NewQueryParameterDefinitions();
NewQuery = NewUserQuery(table.ExternalName, table, expression, parameters, false);
if (NewQuery != null)
{
// Request the newly created query to run
NewQuery.RunQuery();
}
}
}
/// <summary>
/// The method that handles saving of the constructed query.
/// </summary>
private void SaveNewQuery()
{
var mode = this.NewQueryViewModel.SelectedMode;
if (mode != null)
{
// Get the name
var queryName = this.NewQueryViewModel.QueryName;
// Make sure there is a name
if (string.IsNullOrEmpty(queryName) || String.Compare(queryName, ApplicationResources.Query, StringComparison.OrdinalIgnoreCase) == 0)
{
queryName = string.Concat(ApplicationResources.Query, " (", mode.TableDescriptor.ExternalName, ")");
}
// Make sure it's unique
queryName = UniqueExternalNameFor(queryName);
// Get new Query details from the selected mode
var table = mode.TableDescriptor;
var description = UniqueExternalNameFor(queryName);
var expression = mode.NewQueryExpression();
var parameters = mode.NewQueryParameterDefinitions();
var newQuery = NewUserQuery(description, table, expression, parameters, true);
if (newQuery != null)
{
// Track in Analytics
LiteAnalyticsTracker.TrackQueryCreate(newQuery);
// Request the newly created query to run
newQuery.RunQuery();
}
}
NewQueryViewVisibility = Visibility.Collapsed;
}
#endregion
#region Authentication/Queries Property Changes
/// <summary>
/// Whenever authentication changes, (re)get the queries.
/// </summary>
/// <param name="context">The new authorisation context</param>
/// <param name="isAuthenticated">A flag indicating whether the user is authenticated</param>
protected override void OnAuthenticationChanged(AuthenticationContext context, bool isAuthenticated)
{
base.OnAuthenticationChanged(context, isAuthenticated);
if (isAuthenticated)
{
// Automatically get the queries upon authentication
var ignored = GetQueriesAsync();
// Get the custom queries settings
this.IsCustomQueriesVisible = LiteClientSettingsViewModel.Instance.AllowCustomQueries;
}
else
{
// Not authenticated anymore; get rid of our queries
EmptyQueries();
}
}
#endregion
#region Queries
/// <summary>
/// Empties all queries
/// </summary>
private void EmptyQueries()
{
this.Queries = new SortedObservableCollection<LiteQueryViewModel>(LiteQueryViewModel.LiteQueryViewModelComparer);
}
/// <summary>
/// Gets all queries asynchronousluy
/// </summary>
public async Task GetQueriesAsync()
{
IsBusy = true;
var queryModels = new List<LiteQueryViewModel>();
try
{
// Get the Server Queries
queryModels.AddRange(await this.GetProjectQueries());
// Subsequently get the client queries (is done synchronously)
queryModels.AddRange(await this.GetUserQueries());
}
finally
{
this.Queries = new SortedObservableCollection<LiteQueryViewModel>(LiteQueryViewModel.LiteQueryViewModelComparer, queryModels);
IsBusy = false;
}
}
/// <summary>
/// Gets the query definitions from the server
/// </summary>
/// <returns></returns>
private async Task<IList<LiteQueryViewModel>> GetProjectQueries()
{
var queryViewModels = new List<LiteQueryViewModel>();
if (IsAuthenticated)
{
try
{
var queries = await GetService<IQueryService>().GetQueryDefinitionsAsync();
foreach (var query in queries)
{
if (query.IsUserVisible && (QueryDefinitionFilter == null || QueryDefinitionFilter(query)))
{
queryViewModels.Add(new LiteQueryViewModel(this.Messenger, query));
}
}
}
catch (Exception)
{
// Something went wrong while retrieving the queries
}
}
return queryViewModels;
}
/// <summary>
/// Gets the query definitions as stored in the Isolated Storage
/// </summary>
private async Task<IList<LiteQueryViewModel>> GetUserQueries()
{
var queryViewModels = new List<LiteQueryViewModel>();
try
{
var request = new GetDDRequest()
{
GroupTypes = new ServiceProviderGroupType[] { ServiceProviderGroupType.Business, ServiceProviderGroupType.Analysis }
};
var allSources = await ServiceLocator.Current.GetInstance<ICollectionService>().GetDDAsync(request);
var isolatedStorageQueries = LiteIsolatedStorageManager.Instance.UserQueries;
if (isolatedStorageQueries != null)
{
foreach (var isolatedStorageQuery in isolatedStorageQueries)
{
var userQuery = await isolatedStorageQuery.ToUserQueryViewModel(this.Messenger, allSources);
if (userQuery != null)
{
queryViewModels.Add(userQuery);
}
}
}
}
catch
{
// The stored queries could not be matched with our model
// We could choose to clear the stored client queries
}
return queryViewModels;
}
/// <summary>
/// Saves all client queries to the isolated storage
/// </summary>
private void SaveUserQueries()
{
var queries = this.Queries;
if (queries != null)
{
var isolatedStorageUserQueries = new List<LiteUserQueryStorageModel>();
foreach (var queryViewModel in queries)
{
if (queryViewModel.Query.Context == ServiceProviderDatumContext.User)
{
isolatedStorageUserQueries.Add(new LiteUserQueryStorageModel(queryViewModel));
}
}
// And save the lot
LiteIsolatedStorageManager.Instance.UserQueries = isolatedStorageUserQueries;
}
}
/// <summary>
/// Adds the given client-query to the list of queries
/// </summary>
/// <param parameterName="parameterExternalName">The parameterName to show to the end user</param>
/// <param parameterName="table">The table descriptor that the query belongs to</param>
/// <param parameterName="predicate">The predicate that defines the filter for the query</param>
/// <param parameterName="parameterDefinitions">The parameter definitions defining the functionParameters to be used</param>
private LiteQueryViewModel NewUserQuery(string externalName, FeatureTableDescriptor table, System.Linq.Expressions.Expression predicate, ParameterDefinitionCollection parameterDefinitions, bool addToQueries)
{
LiteQueryViewModel clientQuery = null;
if (IsAuthenticated && Queries != null)
{
var predicateText = predicate != null ? predicate.GeoLinqText(useInternalParameterNames: true) : null;
var queryDefinition = new FeatureCollectionQueryDefinition()
{
ServiceProviderGroup = table.ServiceProviderGroup,
Context = ServiceProviderDatumContext.User,
Name = externalName.ToLower(),
ExternalName = externalName,
TableDescriptor = table,
ParameterDefinitions = parameterDefinitions
};
clientQuery = new LiteQueryViewModel(this.Messenger, queryDefinition, predicateText);
if (addToQueries)
{
Queries.Add(clientQuery);
SaveUserQueries();
}
}
return clientQuery;
}
/// <summary>
/// Remove the specified query
/// </summary>
/// <param parameterName="query">The query to remove</param>
private async void RemoveUserQuery(LiteQueryViewModel query)
{
if (Queries != null && query != null)
{
var caption = ApplicationResources.QueryRemoveTitle;
var removeString = string.Format(ApplicationResources.QueryRemoveStringFormat, query.ExternalName);
var result = await this.MessageBoxService.ShowAsync(removeString, caption, MessageBoxButton.OKCancel, MessageBoxResult.Cancel);
if (result == MessageBoxResult.OK)
{
Queries.Remove(query);
}
if (query.Query != null && query.Query.Context == ServiceProviderDatumContext.User)
{
SaveUserQueries();
}
}
}
/// <summary>
/// Whenever a query is renamed, restore it in the sorted collection
/// </summary>
/// <param parameterName="query">The query that was renamed</param>
private void RenamedQuery(LiteQueryViewModel query)
{
if (Queries != null && query != null)
{
// Might need to be reordered; reinsert the item
Queries.Remove(query);
Queries.Add(query);
SaveUserQueries();
}
}
#endregion
#region Changes in Queries
/// <summary>
/// Attach all queries, making sure we respond to collection changes as well
/// as changes in individual queries
/// </summary>
private void AttachQueries()
{
if (_queries != null)
{
_queries.CollectionChanged += QueriesCollectionChanged;
foreach (var query in _queries)
{
AttachQuery(query);
}
}
}
/// <summary>
/// Detach from the queries, since we are setting up a new query collection.
/// Detach from all individual queries as well
/// </summary>
private void DetachQueries()
{
if (_queries != null)
{
_queries.CollectionChanged -= QueriesCollectionChanged;
foreach (var query in _queries)
{
DetachQuery(query);
}
}
}
/// <summary>
/// Callback for changes in the queries collection; detach all old items (removed items) and attach
/// to new queries.
/// </summary>
void QueriesCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (LiteQueryViewModel item in e.OldItems)
{
DetachQuery(item);
}
}
if (e.NewItems != null)
{
foreach (LiteQueryViewModel item in e.NewItems)
{
AttachQuery(item);
}
}
}
/// <summary>
/// Attach to the query's remove command and property change notification
/// </summary>
/// <param name="query">The query to attach to</param>
private void AttachQuery(LiteQueryViewModel query)
{
if (query != null)
{
query.RequestRemoveQuery += RemoveUserQuery;
query.PropertyChanged += QueryPropertyChanged;
}
}
/// <summary>
/// Detach from the query's remove command and property change notification
/// </summary>
/// <param name="query">The query to detach from</param>
private void DetachQuery(LiteQueryViewModel query)
{
if (query != null)
{
query.RequestRemoveQuery -= RemoveUserQuery;
query.PropertyChanged -= QueryPropertyChanged;
}
}
/// <summary>
/// Callback for property changes in a query
/// </summary>
void QueryPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == LiteQueryViewModel.ExternalNamePropertyName)
{
var query = sender as LiteQueryViewModel;
RenamedQuery(query);
}
}
#endregion
#region Properties
/// <summary>
/// A flag indicating whether we are busy
/// </summary>
public bool IsBusy
{
get { return _isBusy; }
set
{
if (_isBusy != value)
{
_isBusy = value;
RaisePropertyChanged(IsBusyPropertyName);
}
}
}
/// <summary>
/// Holds an observable collection of all queries (server as well as client)
/// </summary>
public SortedObservableCollection<LiteQueryViewModel> Queries
{
get { return _queries; }
set
{
if (_queries != value)
{
if (_queries != null)
{
DetachQueries();
}
var oldQueries = _queries;
_queries = value;
if (_queries != null)
{
AttachQueries();
}
RaisePropertyChanged(QueriesPropertyName, oldQueries, _queries, true);
}
}
}
/// <summary>
/// The query filter, indicating which queries are allowed
/// </summary>
public Predicate<FeatureCollectionQueryDefinition> QueryDefinitionFilter
{
get { return _queryDefinitionFilter; }
set
{
if (_queryDefinitionFilter != value)
{
_queryDefinitionFilter = value;
// If the filter changes, get all queries afresh. Since this is a task,
// suppress the warning by assigning the result
var ignored = GetQueriesAsync();
}
}
}
/// <summary>
/// Holds the new Query
/// </summary>
public LiteQueryViewModel NewQuery
{
get { return _newQuery; }
set
{
if (value != _newQuery)
{
_newQuery = value;
RaisePropertyChanged(NewQueryPropertyName);
}
}
}
/// <summary>
/// The view model handling new queries
/// </summary>
public LiteNewUserQueryViewModel NewQueryViewModel
{
get { return _newQueryViewModel; }
set
{
if (_newQueryViewModel != value)
{
_newQueryViewModel = value;
RaisePropertyChanged(NewQueryViewModelPropertyName);
}
}
}
/// <summary>
/// Indicates whether an active QuickFind Query should be run automatically
/// when the OpenCommand is executed.
/// </summary>
public Visibility NewQueryViewVisibility
{
get { return _newQueryViewVisibility; }
set
{
if (value != _newQueryViewVisibility)
{
_newQueryViewVisibility = value;
CheckCommands();
RaisePropertyChanged(NewQueryViewVisibilityPropertyName);
}
}
}
/// <summary>
/// Flag indicating whether the Custom Query button is visible
/// </summary>
public bool IsCustomQueriesVisible
{
get { return _isCustomQueriesVisible; }
set
{
if (_isCustomQueriesVisible != value)
{
_isCustomQueriesVisible = value;
RaisePropertyChanged(CustomQueriesVisibilityPropertyName);
}
}
}
/// <summary>
/// The custom query button's visibility
/// </summary>
public Visibility CustomQueriesVisibility
{
get { return _isCustomQueriesVisible ? Visibility.Visible : Visibility.Collapsed; }
}
#endregion
}
}
|
using UnityEngine;
using System.Collections;
// Super-simple health pack script
public class Medpac : MonoBehaviour {
public int healAmount = 30; // Usually out of 100 (max health)
void OnTriggerEnter2D(Collider2D collider) {
Health health = collider.gameObject.GetComponent<Health>();
bool healed = health.AddHealth(healAmount);
// Don't use up the medpac unless the player was actually healed (not at max health)
if (healed)
Destroy(gameObject);
}
}
|
using FamilyAccounting.DAL.Entities;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace FamilyAccounting.DAL.Interfaces
{
public interface IWalletRepository
{
public Task<IEnumerable<Wallet>> GetAsync();
public Task<Wallet> GetAsync(int id);
public Task<Wallet> UpdateAsync(int id, Wallet wallet);
public Task<int> DeleteAsync(int id);
public Task<Wallet> CreateAsync(Wallet wallet);
public Task<IEnumerable<Transaction>> GetTransactionsAsync(int walletId);
public Task<IEnumerable<Transaction>> GetTransactionsAsync(int walletId, DateTime from, DateTime to);
public Task<Wallet> MakeActiveAsync(int id);
public IEnumerable<Wallet> Get();
public Wallet Get(int id);
public Wallet Update(int id, Wallet wallet);
public int Delete(int id);
public Wallet Create(Wallet wallet);
public IEnumerable<Transaction> GetTransactions(int walletId);
public IEnumerable<Transaction> GetTransactions(int walletId, DateTime from, DateTime to);
public Wallet MakeActive(int id);
}
}
|
using System;
using Umbraco.Core.Models.PublishedContent;
namespace Uintra.Core.Feed.Services
{
public interface IFeedContentService
{
Enum GetCreateActivityType(IPublishedContent content);
}
}
|
namespace Inventory.Models.Enums
{
/// <summary>
/// Тип заказа
/// </summary>
public enum OrderTypeEnum
{
/// <summary>
/// Доставка
/// </summary>
Delivery = 1,
/// <summary>
/// На вынос
/// </summary>
Takeaway = 2,
/// <summary>
/// Дозаказ доставка
/// </summary>
OrderDelivery = 3,
/// <summary>
/// Дозаказ самовынос
/// </summary>
OrderTakeaway = 4,
/// <summary>
/// Food Tigra
/// </summary>
FoodTigra = 5
}
}
|
public class WarriorModel : UnitModel
{
[Inject]
public AISolver AISolver { get; set; }
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TreeSolver
{
public class Patient
{
public int firstIntervalStart;
public int firstIntervalEnd;
public int personalGapTime;
public int secondIntervalLength;
public int id;
public Patient(int firstIntervalStart, int firstIntervalEnd, int personalGapTime, int secondIntervalLength, int id)
{
this.firstIntervalStart = firstIntervalStart;
this.firstIntervalEnd = firstIntervalEnd;
this.personalGapTime = personalGapTime;
this.secondIntervalLength = secondIntervalLength;
this.id = id;
}
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Salle.Model.Salle;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Salle.Model.Salle.Tests
{
[TestClass()]
public class GroupeClientTest
{
[TestMethod()]
public void GroupeClientTests()
{
GroupeClient test = new GroupeClient();
//Assert.IsNotNull(test);
foreach (IClient client in test._Clients) Assert.IsNotNull(client);
//Assert.AreEqual(nbrType, 1);
// Assert.IsNotNull();
//Assert.AreEqual(nbrClient, nbrClientTest);
/*
List<IClient> Clients = new List<IClient>();
Clients.Add(ClientFactory.getClient("Client1"));
Assert.IsNotNull(Clients);
*/
}
[TestMethod()]
public void suivreChefRangTest()
{
Assert.Fail();
}
[TestMethod()]
public void clientsCommandeTest()
{
Assert.Fail();
}
[TestMethod()]
public void quitterTableTest()
{
List<IClient> Clients = new List<IClient>();
Clients.Add(ClientFactory.getClient("Client1"));
Clients = null;
Assert.IsNull(Clients);
}
[TestMethod()]
public void updateTest()
{
Assert.Fail();
}
}
}
|
using BLL.Services;
using System.Windows;
using System.Windows.Controls;
using UI.ViewModels;
namespace UI.Pages
{
/// <summary>
/// Логика взаимодействия для CategoriesListPage.xaml
/// </summary>
public partial class CategoriesListPage : Page
{
private readonly CategoriesListViewModel _viewModel;
public CategoriesListPage()
{
InitializeComponent();
_viewModel = new CategoriesListViewModel(ServiceProviderContainer.GetService<CategoryService>());
DataContext = _viewModel;
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
ShowCategoryModificationWindow(new CategoryModificationPage(null));
UpdateViewModelServices();
}
private void ChangeButton_Click(object sender, RoutedEventArgs e)
{
if (_viewModel.IsCurrentCategoryModelNotNull)
{
ShowCategoryModificationWindow(new CategoryModificationPage(_viewModel.CurrentCategoryModel));
UpdateViewModelServices();
}
}
private void ShowCategoryModificationWindow(CategoryModificationPage content)
{
var dialogWindow = new DialogWindow()
{
Owner = Window.GetWindow(this),
Content = content
};
dialogWindow.ShowDialog();
}
public void UpdateViewModelServices()
{
_viewModel.UpdateServices(ServiceProviderContainer.GetService<CategoryService>());
}
}
}
|
using eMAM.Data.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace eMAM.UI.Models
{
public class EmailViewModel
{
public int Id { get; set; }
public string GmailIdNumber { get; set; }
public int StatusId { get; set; }
public Status Status { get; set; }
//TODO: to be encrypted
public string Body { get; set; }
public int SenderId { get; set; }
public Sender Sender { get; set; }
public DateTime DateReceived { get; set; }
public string Subject { get; set; }
public ICollection<Attachment> Attachments { get; set; }
public bool AreAttachments { get; set; }
public int? CustomerId { get; set; }
public Customer Customer { get; set; }
public DateTime InitialRegistrationInSystemOn { get; set; }
public DateTime SetInCurrentStatusOn { get; set; }
public DateTime SetInTerminalStatusOn { get; set; }
public string OpenedById { get; set; }
public User OpenedBy { get; set; }
public string ClosedById { get; set; }
public User ClosedBy { get; set; }
public ICollection<EmailViewModel> SearchResults { get; set; } = new List<EmailViewModel>();
public bool HasPreviousPage { get; set; }
public bool HasNextPage { get; set; }
public int PageIndex { get; set; }
public int TotalPages { get; set; }
public bool WorkInProcess { get; set; }
public string WorkingById { get; set; }
public User WorkingBy { get; set; }
public string PreviewedById { get; set; }
public User PreviewedBy { get; set; }
public bool UserIsManager { get; set; }
public string Muted { get; set; }
[MinLength(10)]
[Required]
public string CustomerEGN { get; set; }
[MinLength(6)]
[Required]
public string CustomerPhoneNumber { get; set; }
public TimeSpan InCurrentStatusSince { get; set; }
public bool FilterOnlyNotValid { get; set; }
public string FilterByUser { get; set; }
public ICollection<string> UserNames { get; set; } = new List<string>();
public string FilterClosedStatus { get; set; }
public List<string> FilterClosedStatusList { get; set; }
public bool RowShouldBeEdited { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyHeroKill.Model.Weapons
{
public interface IDefenseWeapon
{
/// <summary>
/// 是几星
/// </summary>
int Star { get; set; }
/// <summary>
/// 没星增加的几率
/// </summary>
int StarDeltaRate { get; set; }
/// <summary>
/// 是几级
/// </summary>
int Level { get; set; }
int BaseTriggerRate { get; set; }
/// <summary>
/// 突发概率
/// </summary>
int TriggerRate { get; }
/// <summary>
/// 触发颜色
/// </summary>
MyHeroKill.Model.Enums.ECardColors TriggerColor { get; set; }
/// <summary>
/// 可以免疫杀
/// </summary>
bool CanDefenceHeiSha { get; set; }
bool CanDefenceHongSha { get; set; }
bool CanDefenceFenghuolangyan { get; set; }
bool CanDefenceWanjianqifa { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Security.Cryptography;
namespace Kingdee.CAPP.Common
{
/// <summary>
/// 类型说明:通用帮助类
/// 作 者:jason.tang
/// 完成时间:2012-12-20
/// </summary>
public static class CommonHelper
{
//拖动无无边框的窗体
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;
/// <summary>
/// 方法说明:通用的文本框输入校验方法,可以校验转换错误。
/// 一般在TextBox对象的Leave事件委托函数中调用此方法。
/// 转换成功返回true,表示输入合法;否则返回false。
/// 作 者:jason.tang
/// 完成时间:2012-12-20
/// </summary>
/// <param name="tb">要校验的文本框</param>
/// <param name="allowedType">允许输入的类型</param>
/// <param name="parseErrorMsg">转换失败的错误提示</param>
/// <returns></returns>
public static bool ValidateTextBoxInput(TextBox tb, Type allowedType, string parseErrorMsg)
{
string txt = tb.Text;
//使用反射技术获取目标类型的TryParse方法
System.Reflection.MethodInfo methodTryParse = allowedType.GetMethod("TryParse", new Type[] { typeof(string), allowedType.MakeByRefType() });
//实例化一个目标类型对象。TryParse方法需要这样的一个out参数。
object value = Activator.CreateInstance(allowedType);
//调用TryParse方法,其返回值标志着是否转换成功。
object parseSuccess = methodTryParse.Invoke(null, new object[] { txt, value });
if (Convert.ToBoolean(parseSuccess))//若转换成功,什么也不做
{
return true;
}
else//若转换失败,提示错误,并使此文本框获得焦点,以便重新输入
{
if (!string.IsNullOrEmpty(parseErrorMsg))
{
MessageBox.Show(parseErrorMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
tb.Focus();
}
return false;
}
}
/// <summary>
/// 方法说明:校验输入是否为空
/// 作 者:jason.tang
/// 完成时间:2012-12-26
/// </summary>
/// <param name="controls">控件集合</param>
/// <returns></returns>
public static bool CheckNullInput(List<Control> controls)
{
foreach (Control control in controls)
{
if (control is TextBox)
{
if (string.IsNullOrEmpty(((TextBox)control).Text))
{
string name = ResourceNotice.ResourceManager.GetString(control.Name.Substring(3));
MessageBox.Show(string.Format("{0}不能为空", name), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
control.Focus();
return false;
}
}
else if (control is ComboBox)
{
if (string.IsNullOrEmpty(((ComboBox)control).SelectedItem.ToString()))
{
string name = ResourceNotice.ResourceManager.GetString(control.Name.Substring(5));
MessageBox.Show(string.Format("{0}不能为空", name), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
control.Focus();
return false;
}
}
}
return true;
}
public static void MoveNoneBorderForm(Form form)
{
ReleaseCapture();
SendMessage(form.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}
public static string Md5Hash(string input, Guid salt)
{
return Md5Hash(string.Format(CultureInfo.InvariantCulture, "{0}{1}", input, salt));
}
public static string Md5Hash(string input)
{
using (var md5Hash = MD5.Create())
{
// Convert the input string to a byte array and compute the hash.
var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// BitConverter类将基础数据类型与字节数组相互转换
// ToString()将指定的字节数组的每个元素的数值转换为它的等效十六进制字符串表示形式(以"-"分隔)。
return BitConverter.ToString(data).Replace("-", null);
}
}
}
}
|
using Tools;
namespace _057
{
class Program
{
static void Main(string[] args)
{
Decorators.Benchmark(Solve, 1000);
}
private static int Solve(int nToTest)
{
var numerator = new LongInteger(3);
var denominator = new LongInteger(2);
int res = 0;
for (int i = 0; i < nToTest; i++)
{
if (numerator.ToString().Length > denominator.ToString().Length)
{
res++;
}
var temp = denominator;
denominator += numerator;
numerator += 2 * temp;
}
return res;
}
}
}
|
using System;
using Microsoft.Xna.Framework.Graphics;
namespace Project371
{
abstract class RenderableComponent : Component, IRenderable
{
private bool visible = true;
public bool Visible
{
get { return this.visible; }
set
{
if (this.visible != value)
{
this.visible = value;
VisibilityChanged?.Invoke(this, EventArgs.Empty);
}
}
}
public event EventHandler<EventArgs> VisibilityChanged;
public RenderableComponent(string name)
: base(name)
{
VisibilityChanged += OnVisibilityChanged;
}
public abstract void Render();
/// <summary>
/// Invoked when the Visibility property is changed.
/// </summary>
/// <param name="sender">Updated component.</param>
/// <param name="e"></param>
public virtual void OnVisibilityChanged(object sender, EventArgs e) { }
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using com.Sconit.Entity.SYS;
namespace com.Sconit.Entity.SI.SAP
{
[Serializable]
public partial class SAPPPMES0002 : EntityBase
{
#region O/R Mapping Properties
public Int32 Id { get; set; }
[Export(ExportName = "SAPPPMES0002", ExportSeq = 10)]
[Display(Name = "SAPPPMES_ZMESSC", ResourceType = typeof(Resources.SI.SAPPPMES))]
public string ZMESSC { get; set; }
[Export(ExportName = "SAPPPMES0002", ExportSeq = 20)]
[Display(Name = "SAPPPMES_ZMESLN", ResourceType = typeof(Resources.SI.SAPPPMES))]
public string ZMESLN { get; set; }
[Export(ExportName = "SAPPPMES0002", ExportSeq = 30)]
[Display(Name = "SAPPPMES_ZPTYPE", ResourceType = typeof(Resources.SI.SAPPPMES))]
public string ZPTYPE { get; set; }
[Export(ExportName = "SAPPPMES0002", ExportSeq = 40)]
[Display(Name = "SAPPPMES_ZComnum", ResourceType = typeof(Resources.SI.SAPPPMES))]
public string ZComnum { get; set; }
[Export(ExportName = "SAPPPMES0002", ExportSeq = 50)]
[Display(Name = "SAPPPMES_ZMESGUID", ResourceType = typeof(Resources.SI.SAPPPMES))]
public string ZMESGUID { get; set; }
[Export(ExportName = "SAPPPMES0002", ExportSeq = 60)]
[Display(Name = "SAPPPMES_ZCSRQSJ", ResourceType = typeof(Resources.SI.SAPPPMES))]
public DateTime ZCSRQSJ { get; set; }
[Export(ExportName = "SAPPPMES0002", ExportSeq = 90)]
[Display(Name = "SAPPPMES_Status", ResourceType = typeof(Resources.SI.SAPPPMES))]
public Int32 Status { get; set; }
[Export(ExportName = "SAPPPMES0002", ExportSeq = 70)]
[Display(Name = "SAPPPMES_BatchNo", ResourceType = typeof(Resources.SI.SAPPPMES))]
public string BatchNo { get; set; }
[Export(ExportName = "SAPPPMES0002", ExportSeq = 80)]
[Display(Name = "SAPPPMES_UniqueCode", ResourceType = typeof(Resources.SI.SAPPPMES))]
public string UniqueCode { get; set; }
public string OrderType { get; set; }
[Export(ExportName = "SAPPPMES0002", ExportSeq = 90)]
[Display(Name = "SAPPPMES_CancelDate", ResourceType = typeof(Resources.SI.SAPPPMES))]
public DateTime CancelDate { get; set; }
#endregion
public override int GetHashCode()
{
if (Id != 0)
{
return Id.GetHashCode();
}
else
{
return base.GetHashCode();
}
}
public override bool Equals(object obj)
{
SAPPPMES0002 another = obj as SAPPPMES0002;
if (another == null)
{
return false;
}
else
{
return (this.Id == another.Id);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Braford_Identity.Models
{
public class Ticket
{
[Key]
public int Id { get; set; }
public string user { get; set; }
public DateTime time { get; set; }
public string issue { get; set; }
public string area_of_issue { get; set; }
public string resolution { get; set; }
public string status { get; set; }
}
}
|
using IBLLService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Common;
using System.ComponentModel;
using ShengUI.Helper;
using Common.Attributes;
using MODEL.ViewPage;
using MODEL.ActionModel;
using MODEL.ViewModel;
using MODEL.DataTableModel;
namespace ShengUI.Logic.Admin
{
[AjaxRequestAttribute]
public class PermissionController : Controller
{
public IFW_PERMISSION_MANAGER PermissionManager = OperateContext.Current.BLLSession.IFW_PERMISSION_MANAGER;
[DefaultPage]
[ActionParent]
[ActionDesc("权限维护页")]
[Description("[权限维护页]按钮管理")]
public ActionResult PermissionInfo()
{
var data = PermissionManager.GetPermission();
ViewBag.PermissionList = data;
//UserOperateLog.WriteOperateLog("[系统权限管理]浏览系统权限维护页" + SysOperate.Load.ToMessage(true));
return View();
}
[ActionDesc("获取动作sql")]
[Description("[权限维护页]请求所有控制器的动作信息")]
public ActionResult GetAllAction()
{
DataTableRequest gridRequest = new DataTableRequest(HttpContext);
var list = PermissionManager.GetListBy(p => true).ToList();
var data = ConfigSettings.GetAllAction();
string sqlstr = @" INSERT INTO FW_PERMISSION (PERMISSION_ID, PERMISSION_PID, NAME, AREANAME, CONTROLLERNAME, ACTIONNAME, ISLINK, LINKURL, REMARK, ISSHOW, ISBUTTON, CREATE_DT,SEQ_NO ) VALUES('{0}','{1}',N'{2}','{3}','{4}','{5}','{6}','{7}',N'{8}','{9}','{10}',{11},{12});</BR>";
int i = 1;
StringBuilder sb = new StringBuilder();
foreach (var item in data)
{
if (list.Where(p => p.PERMISSION_ID == item.CD).Count() <= 0)
{
sb.Append(string.Format(sqlstr, item.CD, item.PCD, item.Name, "Admin", item.ControllerName, item.ActionName, item.IsLink, item.LinkUrl, item.Description, "Y", item.IsButton, "Getdate()", i));
}
i++;
}
return Content(sb.ToString());
//忽略掉公共页面的权限动作
//return this.JsonFormat(
// new DataTableGrid()
// {
// rows = LINQHelper.GetIenumberable<MVCAction>(data,
// p => p.ControllerName.ToLower() != "",
// q => gridRequest.SortOrder?"DESC":"ASC", 10000,
// gridRequest.PageNumber),
// total = data.Count()
// });
}
///// <summary>
///// 请求权限功能列表信息
///// </summary>
///// <returns></returns>
//[Description("[系统权限维护页Ajax请求]请求权限功能列表信息(返回Grid)(主页必须)")]
//public ActionResult GetPermissionForGrid()
//{
// EasyUIGridRequest request = new EasyUIGridRequest(HttpContext);
// return this.JsonFormat(PermissionManager.GetPermissionGridTree(request));
//}
//[Description("[系统权限维护页]添加动作")]
//[EasyUIExceptionResult]
//public ActionResult Add()
//{
// bool status = false;
// try
// {
// ViewModelButton viewModel = new ViewModelButton(HttpContext);
// viewModel.pRemark =
// !viewModel.pActionName.IsNullOrEmpty() && !viewModel.pControllerName.IsNullOrEmpty() ? ConfigSettings.GetAllAction()
// .Where(p => p.ActionName == viewModel.pActionName && p.ControllerName == viewModel.pControllerName)
// .SingleOrDefault()
// .Description
// : "";
// PermissionManager.Add(ViewModelButton.ToEntity(viewModel));
// }
// catch (Exception e)
// {
// UserOperateLog.WriteOperateLog("[系统权限管理]添加权限动作信息" + SysOperate.Add.ToMessage(status), e.ToString());
// }
// UserOperateLog.WriteOperateLog("[系统权限管理]添加权限动作信息" + SysOperate.Add.ToMessage(status));
// return this.JsonFormat(status, status, SysOperate.Add);
//}
//[Description("[系统权限维护页]修改动作")]
//[EasyUIExceptionResult]
//public ActionResult Update()
//{
// var model = new MODEL.Sample_Permission();
// string[] ModifyParas = { "pAreaName", "pActionName", "pName", "pIsShow", "pScript", "pIco", "pControllerName", "pIsButton", "pOrder", "pRemark" };
// bool status = false;
// try
// {
// ViewModelButton viewModel = new ViewModelButton(HttpContext);
// model.pId = viewModel.pId;
// model.pAreaName = viewModel.pAreaName;
// model.pActionName = viewModel.pActionName;
// model.pName = viewModel.pName;
// model.pIsShow = viewModel.pIsShow;
// model.pScript = viewModel.pScript;
// model.pIco = viewModel.pIco;
// model.pControllerName = viewModel.pControllerName;
// model.pIsButton = viewModel.pIsButton;
// //model.pParentId = viewModel.pParentId;
// model.pOrder = viewModel.pOrder;
// model.pRemark =
// !viewModel.pActionName.IsNullOrEmpty() && !viewModel.pControllerName.IsNullOrEmpty() ?
// ConfigSettings.GetAllAction()
// .Where(p => p.ActionName == viewModel.pActionName && p.ControllerName == viewModel.pControllerName)
// .SingleOrDefault()
// .Description
// : "";
// PermissionManager.Modify(model, ModifyParas);
// status = true;
// }
// catch (Exception e)
// {
// UserOperateLog.WriteOperateLog("[系统权限管理]修改权限动作信息ID:" + model.pId + SysOperate.Update.ToMessage(status), e.ToString());
// return this.JsonFormat(status, status, SysOperate.Update);
// }
// UserOperateLog.WriteOperateLog("[系统权限管理]修改权限动作信息ID:" + model.pId + SysOperate.Update.ToMessage(status));
// return this.JsonFormat(status, status, SysOperate.Update);
//}
//[Description("[系统权限维护页]软删除动作")]
//[EasyUIExceptionResult]
//public ActionResult Delete()
//{
// ViewModelButton viewModel = new ViewModelButton(HttpContext);
// MODEL.Sample_Permission model = new MODEL.Sample_Permission();
// model.pId = viewModel.pId;
// model.pIsDel = true;
// bool status = false;
// try
// {
// PermissionManager.Modify(model, "pIsDel");
// status = true;
// }
// catch (Exception e)
// {
// UserOperateLog.WriteOperateLog("[系统权限管理](软)删除权限动作信息ID:" + model.pId + SysOperate.Delete.ToMessage(status),e.ToString());
// return this.JsonFormat(status, status, SysOperate.Update);
// }
// UserOperateLog.WriteOperateLog("[系统权限管理](软)删除权限动作信息ID:" + model.pId + SysOperate.Delete.ToMessage(status));
// return this.JsonFormat(status, status, SysOperate.Delete);
//}
//[Description("[系统权限维护页]永久删除动作")]
//[EasyUIExceptionResult]
//public ActionResult RealDelete()
//{
// var pid = TypeParser.ToInt32(HttpContext.Request["pId"]);
// MODEL.Sample_Permission model = new MODEL.Sample_Permission();
// model.pId = pid;
// bool status = false;
// try
// {
// PermissionManager.Del(model);
// status = true;
// }
// catch (Exception e)
// {
// UserOperateLog.WriteOperateLog("[系统权限管理](永久)删除权限动作信息ID:" + model.pId + SysOperate.Delete.ToMessage(status),e.ToString());
// return this.JsonFormat(status, status, SysOperate.Update);
// }
// UserOperateLog.WriteOperateLog("[系统权限管理](永久)删除权限动作信息ID:" + model.pId + SysOperate.Delete.ToMessage(status));
// return this.JsonFormat(status, status, SysOperate.Delete);
//}
}
}
|
using System.Collections;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
public class CharacterDialogueJsonParser : MonoBehaviour
{
// this is very inextensible but dont really need to extend for now
[SerializeField]
private List<string> _nonHostileGenDialogue;
private List<string> _hostileGenDialogue;
private List<string> _nonHostileCbtDialogue;
private List<string> _hostileCbtDialogue;
[SerializeField]
TextAsset nonHostileGen;
[SerializeField]
TextAsset nonHostileCbt;
[SerializeField]
TextAsset hostileGen;
[SerializeField]
TextAsset hostileCbt;
private void Awake()
{
DontDestroyOnLoad(this);
/* _nonHostileGenDialogue = JsonConvert.DeserializeObject<List<string>>(nonHostileGen.text);
_hostileGenDialogue = JsonConvert.DeserializeObject<List<string>>(hostileGen.text);
_nonHostileCbtDialogue = JsonConvert.DeserializeObject<List<string>>(nonHostileCbt.text);
_hostileCbtDialogue = JsonConvert.DeserializeObject<List<string>>(hostileCbt.text);*/
}
public List<string> GetGeneralDialogue(CharacterPersonalityType type)
{
List<string> temp = new List<string>();
switch (type)
{
case CharacterPersonalityType.Hostile:
temp = _hostileGenDialogue;
break;
case CharacterPersonalityType.Nonhostile:
temp = _nonHostileGenDialogue;
break;
}
return temp;
}
public List<string> GetCombatDialogue(CharacterPersonalityType type)
{
List<string> temp = new List<string>();
switch (type)
{
case CharacterPersonalityType.Hostile:
temp = _hostileCbtDialogue;
break;
case CharacterPersonalityType.Nonhostile:
temp = _nonHostileCbtDialogue;
break;
}
return temp;
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dat2csv
{
class Program
{
public class Dat2CsvConverter
{
static Encoding _encoding_gb2312 = Encoding.GetEncoding(936);
public static void ConvertToCsv(string dataFilePath)
{
if (!File.Exists(dataFilePath))
{
throw new FileNotFoundException(dataFilePath);
}
DateTime lastWriteTime = File.GetLastWriteTime(dataFilePath);
DatFileHead head;
#region 这些信息相当于成员变量了都
//dat文件的字节缓冲区
byte[] datFileBuffer;
//点名点号list
List<TagNameTagID> tagNameTagIDs;
//搜集周期类型信息
CollectInfo[] collectInfos;
//搜集索引表在dat中的偏移
int indexStartPos = 0;
//一个历史点信息的大小
const int SizeOfOneHistAnaTagValue = 5;
#endregion
datFileBuffer = File.ReadAllBytes(dataFilePath);
using (MemoryStream ms = new MemoryStream(datFileBuffer, false))
{
using (BinaryReader br = new BinaryReader(ms))
{
head = new DatFileHead();
head.Version = br.ReadInt32();
head.DDOffset = br.ReadInt32();
head.DDLength = br.ReadInt32();
head.IndexOffset = br.ReadInt32();
head.IndexLength = br.ReadInt32();
head.DataOffset = br.ReadInt32();
head.DataLength = br.ReadInt32();
//获取所有点名点号
int allTagCount = head.DDLength / TagNameTagID.Size;
tagNameTagIDs = new List<TagNameTagID>(allTagCount);
ms.Position = head.DDOffset;
//读取点名点号列表
for (int i = 0; i < allTagCount; i++)
{
byte[] tagNameBytes_gb2312 = br.ReadBytes(12);
string tagName = _encoding_gb2312.GetString(tagNameBytes_gb2312);
tagName = tagName.Trim(new char[] { '\0' });
int tagID = br.ReadInt16();
tagNameTagIDs.Add(new TagNameTagID { TagName = tagName, TagID = tagID });
}
//将点名点号按照点号进行排序
tagNameTagIDs.Sort();
//搜集索引表偏移
indexStartPos = head.IndexOffset;
ms.Position = indexStartPos;
//1.获取搜集周期个数
int diffPeriodCount = br.ReadInt16();
//将流定位到搜集类型信息处
ms.Position += 8;
collectInfos = new CollectInfo[diffPeriodCount];
#region 填充各个搜集周期信息
for (int i = 0; i < diffPeriodCount; i++)
{
collectInfos[i] = new CollectInfo();
//1.搜集周期
short period = br.ReadInt16();
collectInfos[i].Period = period;
//2.此周期包含的组数
short grpCount = br.ReadInt16();
collectInfos[i].GroupCount = grpCount;
//3.十分钟点个数
int tagCountInTenMinutes = br.ReadInt32();
collectInfos[i].TagCountInTenMinutes = tagCountInTenMinutes;
//4.组信息偏移
int grpInfoOffset = br.ReadInt32();
collectInfos[i].GroupInfoOffset = grpInfoOffset;
//5.
ms.Position += 2;
}
//遍历各个搜集周期
for (int i = 0; i < diffPeriodCount; i++)
{
//遍历搜集周期中的各个组信息,并以第一组信息为出发点对数据进行搜集
for (int j = 0; j < collectInfos[i].GroupCount; j++)
{
short secondOffset = br.ReadInt16();
short maxTagCount = br.ReadInt16();
short currentTagCount = br.ReadInt16();
short initTagCount = br.ReadInt16();
int tagIDOffset = br.ReadInt32();
int tagDataOffset = br.ReadInt32();
ms.Position += 6;
//以第一组搜集信息为出发点进行搜集
if (secondOffset == 1)
{
collectInfos[i].MaxTagCount = maxTagCount;
collectInfos[i].CurrentTagCount = currentTagCount;
collectInfos[i].TagIDOffset = tagIDOffset;
collectInfos[i].TagDataOffset = tagDataOffset + head.DataOffset;
}
else
{
collectInfos[i].MaxTagCount += maxTagCount;
collectInfos[i].CurrentTagCount += currentTagCount;
//collectInfos[i].TagIDOffset = tagIDOffset;
//collectInfos[i].TagDataOffset = tagDataOffset;
}
}
}
//填充点号信息
for (int i = 0; i < diffPeriodCount; i++)
{
int tagCount = collectInfos[i].CurrentTagCount;
collectInfos[i].TagIDs = new List<int>(tagCount);
ms.Position = indexStartPos + collectInfos[i].TagIDOffset;
//读取需要搜集点的点号
for (int j = 0; j < tagCount; j++)
{
int id = br.ReadInt16();
collectInfos[i].TagIDs.Add(id);
}
}
#endregion
//准备读取需要读取的历史点号
#region 读取历史数据,每个搜集周期创建一个文件
for (int periodIndex = 0; periodIndex < diffPeriodCount; periodIndex++)
{
string fileName = Path.GetFileNameWithoutExtension(dataFilePath);
fileName += "_";
fileName += collectInfos[periodIndex].Period.ToString();
fileName += ".csv";
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs, _encoding_gb2312))
{
//写文件头,列举点名
sw.Write(@"时间/点名");
for (int i = 0; i < collectInfos[periodIndex].TagIDs.Count; i++)
{
int tid = collectInfos[periodIndex].TagIDs[i];
int index = tagNameTagIDs.BinarySearch(new TagNameTagID { TagID = tid });
sw.Write("," + tagNameTagIDs[index].TagName);
}
sw.Write(Environment.NewLine);//回车
DateTime time;
time = lastWriteTime.AddMinutes(-10);
//遍历十分钟数据内的每个点
int tagCountInTenMinutes = collectInfos[periodIndex].TagCountInTenMinutes;
for (int tagIndex = 0; tagIndex < tagCountInTenMinutes; tagIndex++)
{
//搜集每个点前,先定位到其在数据区的首地址
ms.Position = collectInfos[periodIndex].TagDataOffset + SizeOfOneHistAnaTagValue * tagIndex;
sw.Write(time.ToLongTimeString());
//遍历
for (int Index = 0; Index < collectInfos[periodIndex].CurrentTagCount; Index++)
{
float value = br.ReadSingle();
sw.Write(",");
if (value<1e-10)
{
sw.Write(0);
}
else
{
//float数值保留四个小数点
sw.Write(value.ToString("F4"));
}
ms.Position += 1;//5字节中,前四个字节表示AV,最后一个字节表示历史值的状态
//定位到这个点的下一个存储位置
ms.Position -= 5;
ms.Position += SizeOfOneHistAnaTagValue * tagCountInTenMinutes;
}
sw.Write(Environment.NewLine);
time = time.AddSeconds(collectInfos[periodIndex].Period);
}
}//end sw
}//end fs
}//end for write a file
#endregion
}
}
}
}
static void Main(string[] args)
{
//args[0] = @"D:\99SE\git\dat2csv\dat2csv\bin\Debug";
string folder = @"D:\99SE\git\dat2csv\dat2csv\bin\Debug";
//var filePaths = Directory.GetFiles(args[0],"*.dat");
var filePaths = Directory.GetFiles(folder, "*.dat");
foreach (var filePath in filePaths)
{
Dat2CsvConverter.ConvertToCsv(filePath);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace St.Eg.M1.Ex3.Interfaces
{
internal class Program
{
/*
* 1. Copy the three classes from Ex2 (done)
* 2. Create the IAnimal interface
* 3. Derive Animal from IAnimal
* 4. Create a method accepting an IAnimal
* 5. In the method, calll MakeSound and print the age
* 6. Create in Main a doc and cat object, and then
* call the method twice, passing the cat and dog object in each call.
* */
private static void Main(string[] args)
{
IAnimal d = new Dog(2);
IAnimal c = new Cat(3);
// TODO: add two calls to our new method
d.MakeSound();
c.MakeSound();
Console.WriteLine("{0} {1}", d.Age, c.Age);
}
// TODO: create method accepting IAnimal, and call MakeSound and print age
///private static void doit(IAmimal animal)
//{
// TODO: call MakeSound and write Age
//}
}
// TODO: create IAnimal Interface
// TODO: Derive Animal from IAnimal
public interface IAnimal
{
int Age { get; set; }
void MakeSound();
}
public abstract class Animal : IAnimal
{
public int Age { get; set; }
public abstract void MakeSound();
}
public class Dog : Animal
{
public Dog()
{
}
public Dog(int age)
{
Age = age;
}
public override void MakeSound()
{
Console.WriteLine("Woof!");
}
public void Hello()
{
}
}
public class Cat : Animal
{
public Cat()
{
}
public Cat(int age)
{
Age = age;
}
public override void MakeSound()
{
Console.WriteLine("Meow!");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Utils;
using System.Windows;
using Nac.Wpf.Common.Control;
using System.Reflection;
using Nac.Common.Control;
using System.ComponentModel;
namespace Nac.Wpf.SectionEditor.NetworkModel {
/// <summary>
/// Defines a node in the view-model.
/// Nodes are connected to other nodes through attached connectors (aka anchor/connection points).
/// </summary>
public class NacWpfBlockViewModel1 : AbstractModelBase {
#region Private Data Members
private NacWpfBlock _block;
private int zIndex = 0;
/// <summary>
/// The size of the node.
///
/// Important Note:
/// The size of a node in the UI is not determined by this property!!
/// Instead the size of a node in the UI is determined by the data-template for the Node class.
/// When the size is computed via the UI it is then pushed into the view-model
/// so that our application code has access to the size of a node.
/// </summary>
private Size size = Size.Empty;
/// <summary>
/// List of input connectors (connections points) attached to the node.
/// </summary>
private ImpObservableCollection<NacWpfConnectorViewModel1> inputConnectors = null;
/// <summary>
/// List of output connectors (connections points) attached to the node.
/// </summary>
private ImpObservableCollection<NacWpfConnectorViewModel1> outputConnectors = null;
/// <summary>
/// Set to 'true' when the node is selected.
/// </summary>
private bool isSelected = false;
#endregion Private Data Members
public NacWpfBlock Block { get { return _block; }
private set {
_block = value;
Position = Base.Position;
Block.PropertyChanged += Block_PropertyChanged;
}
}
public NacBlock Base { get { return _block.Base; } }
public NacWpfBlockViewModel1() {}
public NacWpfBlockViewModel1(NacWpfBlock block) {
Block = block;
}
private void Block_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) {
//PropertyInfo piDst = GetType().GetProperty(e.PropertyName);
//if (piDst != null) {
// PropertyInfo piSrc = sender.GetType().GetProperty(e.PropertyName);
// piDst.SetValue(this, piSrc.GetValue(sender));
//}
OnPropertyChanged(e.PropertyName);
}
public string Description { get { return Block.Description; } set { if (value != Block.Description) { Block.Description = value; OnPropertyChanged("Description"); } } }
//public NacExecutionStatus Status { get { return Block.Status; } set { if (value != Block.Status) { Block.Status = value; OnPropertyChanged("Status"); } } }
//public NacExecutionQuality Quality { get { return Status.Quality; } set { if (value != Block.Quality) { Block.Quality = value; OnPropertyChanged("Quality"); } } }
//public string Name { get { return Block.Name; } set { Block.Name = value; } }
public NacExecutionStatus Status { get { return Block.Status; } set { Block.Status = value;} }
public NacExecutionQuality Quality { get { return Status.Quality; } set { Block.Quality = value; } }
public TimeSpan Countdown { get { return Status.Countdown; } set { Block.Countdown = value; } }
private double _x, _y;
public double X { get { return _x; } set { _x = value; OnPropertyChanged("X"); } }
public double Y { get { return _y; } set { _y = value; OnPropertyChanged("Y"); } }
public Point Position { set { X = value.X; Y = value.Y; } }
/// <summary>
/// The Z index of the node.
/// </summary>
public int ZIndex
{
get
{
return zIndex;
}
set
{
if (zIndex == value)
{
return;
}
zIndex = value;
OnPropertyChanged("ZIndex");
}
}
/// <summary>
/// The size of the node.
///
/// Important Note:
/// The size of a node in the UI is not determined by this property!!
/// Instead the size of a node in the UI is determined by the data-template for the Node class.
/// When the size is computed via the UI it is then pushed into the view-model
/// so that our application code has access to the size of a node.
/// </summary>
public Size Size
{
get
{
return size;
}
set
{
if (size == value)
{
return;
}
size = value;
if (SizeChanged != null)
{
SizeChanged(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Event raised when the size of the node is changed.
/// The size will change when the UI has determined its size based on the contents
/// of the nodes data-template. It then pushes the size through to the view-model
/// and this 'SizeChanged' event occurs.
/// </summary>
public event EventHandler<EventArgs> SizeChanged;
/// <summary>
/// List of input connectors (connections points) attached to the node.
/// </summary>
public ImpObservableCollection<NacWpfConnectorViewModel1> InputConnectors
{
get
{
if (inputConnectors == null)
{
inputConnectors = new ImpObservableCollection<NacWpfConnectorViewModel1>();
inputConnectors.ItemsAdded += new EventHandler<CollectionItemsChangedEventArgs>(inputConnectors_ItemsAdded);
inputConnectors.ItemsRemoved += new EventHandler<CollectionItemsChangedEventArgs>(inputConnectors_ItemsRemoved);
}
return inputConnectors;
}
}
/// <summary>
/// List of output connectors (connections points) attached to the node.
/// </summary>
public ImpObservableCollection<NacWpfConnectorViewModel1> OutputConnectors
{
get
{
if (outputConnectors == null)
{
outputConnectors = new ImpObservableCollection<NacWpfConnectorViewModel1>();
outputConnectors.ItemsAdded += new EventHandler<CollectionItemsChangedEventArgs>(outputConnectors_ItemsAdded);
outputConnectors.ItemsRemoved += new EventHandler<CollectionItemsChangedEventArgs>(outputConnectors_ItemsRemoved);
}
return outputConnectors;
}
}
/// <summary>
/// A helper property that retrieves a list (a new list each time) of all connections attached to the node.
/// </summary>
public ICollection<NacWpfConnectionViewModel1> AttachedConnections
{
get
{
List<NacWpfConnectionViewModel1> attachedConnections = new List<NacWpfConnectionViewModel1>();
foreach (var connector in this.InputConnectors)
{
attachedConnections.AddRange(connector.AttachedConnections);
}
foreach (var connector in this.OutputConnectors)
{
attachedConnections.AddRange(connector.AttachedConnections);
}
return attachedConnections;
}
}
/// <summary>
/// Set to 'true' when the node is selected.
/// </summary>
public bool IsSelected
{
get
{
return isSelected;
}
set
{
if (isSelected == value)
{
return;
}
isSelected = value;
OnPropertyChanged("IsSelected");
}
}
#region Private Methods
/// <summary>
/// Event raised when connectors are added to the node.
/// </summary>
private void inputConnectors_ItemsAdded(object sender, CollectionItemsChangedEventArgs e)
{
foreach (NacWpfConnectorViewModel1 connector in e.Items)
{
connector.ParentNode = this;
connector.Type = NacWpfConnectorType.Input;
}
}
/// <summary>
/// Event raised when connectors are removed from the node.
/// </summary>
private void inputConnectors_ItemsRemoved(object sender, CollectionItemsChangedEventArgs e)
{
foreach (NacWpfConnectorViewModel1 connector in e.Items)
{
connector.ParentNode = null;
connector.Type = NacWpfConnectorType.Undefined;
}
}
/// <summary>
/// Event raised when connectors are added to the node.
/// </summary>
private void outputConnectors_ItemsAdded(object sender, CollectionItemsChangedEventArgs e)
{
foreach (NacWpfConnectorViewModel1 connector in e.Items)
{
connector.ParentNode = this;
connector.Type = NacWpfConnectorType.Output;
}
}
/// <summary>
/// Event raised when connectors are removed from the node.
/// </summary>
private void outputConnectors_ItemsRemoved(object sender, CollectionItemsChangedEventArgs e)
{
foreach (NacWpfConnectorViewModel1 connector in e.Items)
{
connector.ParentNode = null;
connector.Type = NacWpfConnectorType.Undefined;
}
}
#endregion Private Methods
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Runtime.InteropServices;
namespace identity
{
public class Chapter2b
{
public Game1 game;
public Texture2D background, lantern;
public Rectangle border = new Rectangle(0, 183, 1200, 354);
public Rectangle border2 = new Rectangle(659, 47, 451, 628);
public Rectangle border3;
public Rectangle border4;
public Rectangle border5;
public Rectangle border6;
public Rectangle border7;
public Rectangle jumpscare;
public Rectangle lanpos = new Rectangle(900, 330, 80, 108);
public float lantscale = 1;
public static int langet;
private KeyboardState newState;
public SoundEffect getout;
int music = 0;
int exit;
int startexit;
int back;
float opacity = 1;
public Chapter2b(Game1 game)
{
this.game = game;
background = game.Content.Load<Texture2D>("images/broken hallway light");
lantern = game.Content.Load<Texture2D>("images/lantern");
//getout = game.Content.Load<SoundEffect>("Sounds/Get Out Sound");
}
public void Update(GameTime Gametime)
{
KeyboardState keyboardState = Keyboard.GetState();
newState = keyboardState;
if (background == game.Content.Load<Texture2D>("images/broken hallway light"))
{
//y=-1/276x+48/23
Gameplay.KurtOpaque = (float)Math.Abs((-0.00362318840579 * Gameplay.KurtPos.X) + 2.0869);
if (newState.IsKeyDown(Keys.Z))
{
Text.textinitiate = 0;
back = 1;
}
if (back == 0)
{
Text.textinitiate = 6;
}
if (Gameplay.KurtPos.X <= border.X)
{
Gameplay.KurtPos.X = border.X;
}
if (Gameplay.KurtPos.X + 84 >= border.Width)
{
if (back == 1)
{
Gameplay.KurtPos.X = 0;
background = game.Content.Load<Texture2D>("images/light room");
}
else
{
Gameplay.KurtPos.X = border.Width - 84;
}
}
if (Gameplay.KurtPos.Y <= border.Y)
{
Gameplay.KurtPos.Y = border.Y;
}
if (Gameplay.KurtPos.Y + 108 >= border.Y + border.Height)
{
Gameplay.KurtPos.Y = border.Height + border.Y - 108;
}
}
if (background == game.Content.Load<Texture2D>("images/light room"))
{
if (music == 0)
{
//getout.Play();
music = 1;
}
border.Width = 650;
if (Gameplay.KurtPos.X <= border.X)
{
Gameplay.KurtPos.X = border.X;
}
if (Gameplay.KurtPos.Y <= border.Y && Gameplay.KurtPos.X <= border.Width)
{
Gameplay.KurtPos.Y = border.Y;
}
if (Gameplay.KurtPos.Y + 108 >= border.Y + border.Height && Gameplay.KurtPos.X <= border.Width)
{
Gameplay.KurtPos.Y = border.Height + border.Y - 108;
}
if (Gameplay.KurtPos.Y <= border2.Y)
{
Gameplay.KurtPos.Y = border2.Y;
}
if (Gameplay.KurtPos.Y + 108 >= border2.Y + border2.Height)
{
Gameplay.KurtPos.Y = border2.Height + border2.Y - 108;
}
if (Gameplay.KurtPos.X + 84 >= border2.Width + border2.X)
{
Gameplay.KurtPos.X = border2.Width + border2.X - 84;
}
if (Gameplay.KurtPos.X <= border2.X && Gameplay.KurtPos.Y <= border.Y && Gameplay.KurtPos.X >= border.Width + border.X)
{
Gameplay.KurtPos.X = border2.X;
}
if (Gameplay.KurtPos.X <= border2.X && Gameplay.KurtPos.Y + 108 >= border.Y + border.Height && Gameplay.KurtPos.X >= border.Width + border.X)
{
Gameplay.KurtPos.X = border2.X;
}
if (Gameplay.KurtRect.Intersects(lanpos))
{
Text.textinitiate = 4;
lantscale = 0.3f;
langet = 1;
lanpos.X = Gameplay.KurtRect.X + 40;
lanpos.Y = Gameplay.KurtRect.Y + 40;
opacity -= 0.01f;
if (Text.textkey == 1)
{
Text.textinitiate = 0;
background = game.Content.Load<Texture2D>("images/right side loop room");
}
}
}
if (background == game.Content.Load<Texture2D>("images/right side loop room"))
{
opacity += 0.01f;
border = new Rectangle(-100, 45, 1109, 630);
border2 = new Rectangle(0, 309, 848, 0);
border3 = new Rectangle(853, 309, 0, 112);
border4 = new Rectangle(0, 423, 848, 0);
if (Gameplay.KurtPos.X <= border.X)
{
Gameplay.KurtPos.X = border.Width;
background = game.Content.Load<Texture2D>("images/left side loop room");
}
if (Gameplay.KurtPos.X + 84 >= border.Width)
{
Gameplay.KurtPos.X = border.Width - 84;
}
if (Gameplay.KurtPos.Y <= border.Y)
{
Gameplay.KurtPos.Y = border.Y;
}
if (Gameplay.KurtPos.Y + 108 >= border.Y + border.Height)
{
Gameplay.KurtPos.Y = border.Height + border.Y - 108;
}
if (Gameplay.KurtRect.Intersects(border2))
{
Gameplay.KurtPos.Y = border2.Y - 108;
}
if (Gameplay.KurtRect.Intersects(border3))
{
Gameplay.KurtPos.X = border3.X;
}
if (Gameplay.KurtRect.Intersects(border4))
{
Gameplay.KurtPos.Y = border4.Y;
}
}
if (background == game.Content.Load<Texture2D>("images/left side loop room") || (background == game.Content.Load<Texture2D>("images/left side loop room open")))
{
exit = 630 + startexit;
border = new Rectangle(45, 45, 1209, exit);
border2 = new Rectangle(305, 309, 853, 0);
border3 = new Rectangle(300, 309, 0, 112);
border4 = new Rectangle(305, 423, 853, 0);
border5 = new Rectangle(45, 631, 75, 102);
border6 = new Rectangle(145, 690, 1209, 0);
border7 = new Rectangle(150, 680, 0, 400);
jumpscare = new Rectangle(45, 45, 50, 50);
if (Gameplay.KurtPos.X <= border.X)
{
Gameplay.KurtPos.X = border.X;
}
if (Gameplay.KurtPos.X + 84 >= border.Width)
{
Gameplay.KurtPos.X = border.X;
background = game.Content.Load<Texture2D>("images/right side loop room");
}
if (Gameplay.KurtPos.Y <= border.Y)
{
Gameplay.KurtPos.Y = border.Y;
}
if (Gameplay.KurtPos.Y + 108 >= border.Y + border.Height)
{
Gameplay.KurtPos.Y = border.Height + border.Y - 108;
}
//
if (Gameplay.KurtRect.Intersects(border2))
{
Gameplay.KurtPos.Y = border2.Y - 108;
}
if (Gameplay.KurtRect.Intersects(border3))
{
Gameplay.KurtPos.X = border3.X - 84;
}
if (Gameplay.KurtRect.Intersects(border4))
{
Gameplay.KurtPos.Y = border4.Y;
}
if (Gameplay.KurtRect.Intersects(border5))
{
if (startexit != 300) { Text.textinitiate = 5; }
if (newState.IsKeyDown(Keys.Z))
{
startexit = 300;
background = game.Content.Load<Texture2D>("images/left side loop room open");
}
}
else
{
Text.textinitiate = 0;
}
if (Gameplay.KurtRect.Intersects(border6))
{
Gameplay.KurtPos.X = border6.X - 84;
}
if (Gameplay.KurtRect.Intersects(border7))
{
Gameplay.KurtPos.Y = border7.Y - 108;
}
if (Gameplay.KurtRect.Intersects(jumpscare))
{
JumpScare.shock = 1;
}
else
{
JumpScare.shock = 0;
}
//Starts random room
if (Gameplay.KurtPos.Y >= 700)
{
game.level1 += 1;
JumpScare.time = 0;
}
}
}
public void Draw(SpriteBatch spritebatch)
{
spritebatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
if (background == game.Content.Load<Texture2D>("images/light room"))
{ spritebatch.Draw(lantern, new Vector2(lanpos.X, lanpos.Y), null, Color.White, 0, Vector2.Zero, lantscale, SpriteEffects.None, 1); }
spritebatch.Draw(background, Vector2.Zero, null, Color.White * opacity, 0, Vector2.Zero, game.scale, SpriteEffects.None, 1);
spritebatch.End();
}
}
}
|
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace MyKeibaDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("比赛日期: 20141201, 20141202");
Console.WriteLine("马场: 帯広, 水沢, 金沢, 名古屋, 園田");
Console.WriteLine("请等待18秒左右……");
// 帯広 opTrackCd=03&sponsorCd=04
// 水沢 opTrackCd=12&sponsorCd=06
// 金沢 opTrackCd=41&sponsorCd=18
// 名古屋 opTrackCd=43&sponsorCd=33
// 園田 opTrackCd=51&sponsorCd=26
CExcelService.CreateCsvFiles("20141201", "03", "04");
CExcelService.CreateCsvFiles("20141201", "12", "06");
CExcelService.CreateCsvFiles("20141202", "41", "18");
CExcelService.CreateCsvFiles("20141202", "43", "33");
CExcelService.CreateCsvFiles("20141202", "51", "26");
Console.WriteLine("按任意键结束...");
Console.ReadKey();
}
}
}
|
public class Solution {
public IList<IList<string>> GroupAnagrams(string[] strs) {
var res = new List<IList<string>>();
if (strs.Length == 0) return res;
var helperDict = new Dictionary<string, List<string>>();
foreach (var str in strs) {
string orderedStr = new string (str.OrderBy(c => c).ToArray());
if (!helperDict.ContainsKey(orderedStr)) {
helperDict[orderedStr] = new List<string>();
}
helperDict[orderedStr].Add(str);
}
foreach(KeyValuePair<string, List<string>> entry in helperDict)
{
res.Add(entry.Value);
}
return res;
}
}
|
using System;
namespace DDMedi
{
public sealed class DDMediFactory : IDisposable
{
public IBaseDescriptorCollection BaseDescriptorCollection => BasicDescriptorCollection;
internal IInternalBaseDescriptorCollection BasicDescriptorCollection { get; }
internal IInternalSupplierFactory SupplierFactory { get; }
internal IInternalEInputsQueueFactory EInputsQueueFactory { get; }
private ISupplierScopeFactory _scopeFactory;
internal DDMediFactory(
IInternalBaseDescriptorCollection baseDescriptorCollection,
IInternalSupplierFactory supplierfactory,
IInternalEInputsQueueFactory queueFactory)
{
BasicDescriptorCollection = baseDescriptorCollection ?? throw new ArgumentNullException();
SupplierFactory = supplierfactory ?? throw new ArgumentNullException();
EInputsQueueFactory = queueFactory ?? throw new ArgumentNullException();
}
public DDMediFactory SetScopeFactory(ISupplierScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
EInputsQueueFactory.StartAsync(scopeFactory);
return this;
}
public void Dispose()
{
_scopeFactory = null;
BasicDescriptorCollection.Dispose();
SupplierFactory.Dispose();
EInputsQueueFactory.Dispose();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Api.Swashbuckle
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//Register IdentitServer4 authentication library
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000"; // auth server base endpoint (will use to search for disco doc)
options.ApiName = "demo_api"; // required audience of access tokens
options.RequireHttpsMetadata = false; // dev only!
});
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info {Title = "Protected API", Version = "v1"});
options.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Flow = "implicit", // just get token via browser (suitable for swagger SPA)
AuthorizationUrl = "http://localhost:5000/connect/authorize",
Scopes = new Dictionary<string, string> {{"demo_api", "Demo API - full access"}}
});
options.OperationFilter<AuthorizeCheckOperationFilter>(); // Required to use access token
});
}
public void Configure(IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseAuthentication();
// Swagger JSON Doc
app.UseSwagger();
// Swagger UI
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
options.RoutePrefix = string.Empty;
options.OAuthClientId("demo_api_swagger");
options.OAuthAppName("Demo API - Swagger"); // presentation purposes only
});
app.UseMvc();
}
}
public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
var hasAuthorize = context.ControllerActionDescriptor.GetControllerAndActionAttributes(true).OfType<AuthorizeAttribute>().Any();
if (hasAuthorize)
{
operation.Responses.Add("401", new Response { Description = "Unauthorized" });
operation.Responses.Add("403", new Response { Description = "Forbidden" });
operation.Security = new List<IDictionary<string, IEnumerable<string>>>
{
new Dictionary<string, IEnumerable<string>> {{"oauth2", new[] {"demo_api"}}}
};
}
}
}
}
|
namespace Serilog.Tests.Core;
public class LoggerExtensionsTests
{
[Theory]
[InlineData(Debug, Debug)]
[InlineData(Debug, Information)]
[InlineData(Debug, Error)]
[InlineData(Debug, Fatal)]
[InlineData(Debug, Warning)]
public void ShouldEnrichLogEventWhenLevelIsSameOrHigherThanMinLevel(LogEventLevel logMinLevel, LogEventLevel propertyLogLevel)
{
var propValue = Guid.NewGuid();
var propKey = Some.String();
var sink = new CollectingSink();
var logger = new LoggerConfiguration()
.MinimumLevel.Is(logMinLevel)
.WriteTo.Sink(sink)
.CreateLogger();
logger.ForContext(propertyLogLevel, propKey, propValue)
.Write(logMinLevel, string.Empty);
Assert.True(sink.SingleEvent.Properties.ContainsKey(propKey));
Assert.Equal(sink.SingleEvent.Properties[propKey].LiteralValue(), propValue);
}
[Theory]
[InlineData(Debug, Verbose)]
[InlineData(Information, Debug)]
[InlineData(Warning, Information)]
[InlineData(Error, Warning)]
[InlineData(Fatal, Error)]
public void ShouldNotEnrichLogEventsWhenMinLevelIsHigherThanProvidedLogLevel(LogEventLevel logMinLevel, LogEventLevel propertyLogLevel)
{
var propValue = Guid.NewGuid();
var propKey = Some.String();
var sink = new CollectingSink();
var logger = new LoggerConfiguration()
.MinimumLevel.Is(logMinLevel)
.WriteTo.Sink(sink)
.CreateLogger();
logger.ForContext(propertyLogLevel, propKey, propValue)
.Write(logMinLevel, string.Empty);
Assert.False(sink.SingleEvent.Properties.ContainsKey(propKey));
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Base64FileConverter
{
public partial class Base64FileConverterForm : Form
{
public Base64FileConverterForm()
{
InitializeComponent();
}
private void _btnBackToModeSelect_Click(object sender, EventArgs e)
{
_pnlBackToModeSelect.Hide();
_pnlFileToBase64.Hide();
_pnlBase64ToFile.Hide();
_pnlSelectRunMode.Show();
}
private void _btnSelectModeConvertBase64ToFile_Click(object sender, EventArgs e)
{
_pnlSelectRunMode.Hide();
_pnlFileToBase64.Hide();
_pnlBackToModeSelect.Show();
_pnlBase64ToFile.Show();
}
private void _btnSelectModeConvertFileToBase64_Click(object sender, EventArgs e)
{
_pnlSelectRunMode.Hide();
_pnlBase64ToFile.Hide();
_pnlBackToModeSelect.Show();
_pnlFileToBase64.Show();
}
private void _btnSelectFileToConvertToBase64_Click(object sender, EventArgs e)
{
_dlgSelectFileToConvertToBase64.ShowDialog();
}
private void _dlgSelectFileToConvertToBase64_FileOk(object sender, CancelEventArgs e)
{
_txtFileToConvertToBase64.Text = _dlgSelectFileToConvertToBase64.FileName;
}
private void _btnExecuteConvertFileToBase64_Click(object sender, EventArgs e)
{
_txtDecompressedBase64.Text = null;
_txtCompressedBase64.Text = null;
_btnCopyDecompressedToClipboard.Enabled = false;
_btnCopyCompressedToClipboard.Enabled = false;
if (string.IsNullOrWhiteSpace(_txtFileToConvertToBase64.Text))
MessageBox.Show("Enter a file path.", "Error", MessageBoxButtons.OK);
else if (!File.Exists(_txtFileToConvertToBase64.Text))
MessageBox.Show("The file you provided doesn't exist.", "Error", MessageBoxButtons.OK);
else
{
_txtDecompressedBase64.Text = "Processing...";
_txtCompressedBase64.Text = "Processing...";
var bytes = File.ReadAllBytes(_dlgSelectFileToConvertToBase64.FileName);
var base64String = Convert.ToBase64String(bytes);
_txtDecompressedBase64.Text = base64String;
_btnCopyDecompressedToClipboard.Enabled = true;
var compressedBytes = Utilities.Compress(bytes);
var compressedBase64String = Convert.ToBase64String(compressedBytes);
_txtCompressedBase64.Text = compressedBase64String;
_btnCopyCompressedToClipboard.Enabled = true;
}
}
private void _btnCopyDecompressedToClipboard_Click(object sender, EventArgs e)
{
Clipboard.SetText(_txtDecompressedBase64.Text);
}
private void _btnCopyCompressedToClipboard_Click(object sender, EventArgs e)
{
Clipboard.SetText(_txtCompressedBase64.Text);
}
private void _btnSelectFileToSaveBase64_Click(object sender, EventArgs e)
{
_lblSaveFileResult.Hide();
_dlgSaveBase64ToFile.ShowDialog();
}
private void _dlgSaveBase64ToFile_FileOk(object sender, CancelEventArgs e)
{
_lblSaveFileResult.Hide();
_txtFileToSaveFromBase64.Text = _dlgSaveBase64ToFile.FileName;
}
private void _txtFileToSaveFromBase64_TextChanged(object sender, EventArgs e)
{
_lblSaveFileResult.Hide();
}
private void _btnSaveBase64ToFile_Click(object sender, EventArgs e)
{
_lblSaveFileResult.Hide();
var fullFilePath = _txtFileToSaveFromBase64.Text;
if (string.IsNullOrWhiteSpace(_txtBase64ToConvertToFile.Text))
MessageBox.Show("Enter a Base64 string.", "Error", MessageBoxButtons.OK);
else if (string.IsNullOrWhiteSpace(fullFilePath))
MessageBox.Show("Enter a file path.", "Error", MessageBoxButtons.OK);
else if (!Directory.Exists(Path.GetDirectoryName(fullFilePath)))
MessageBox.Show("The directory you provided doesn't exist.", "Error", MessageBoxButtons.OK);
else if (string.IsNullOrWhiteSpace(Path.GetFileName(fullFilePath)))
MessageBox.Show("Enter a file name.", "Error", MessageBoxButtons.OK);
else if (string.IsNullOrWhiteSpace(Path.GetExtension(fullFilePath)))
MessageBox.Show("Enter a file extension.", "Error", MessageBoxButtons.OK);
else
{
if (File.Exists(fullFilePath))
{
// If the file already exists, prompt first to make sure it's ok to overwrite it. If not, cancel.
if (DialogResult.No == MessageBox.Show("This file already exists. Overwrite it?", "Warning: File Already Exists", MessageBoxButtons.YesNo))
return;
}
try
{
var base64 = _txtBase64ToConvertToFile.Text;
var bytes = Convert.FromBase64String(base64);
// Decompress the bytes and save it to a file. If the bytes were already decompressed this doesn't do anything.
File.WriteAllBytes(fullFilePath, Utilities.Decompress(bytes));
_lblSaveFileResult.ForeColor = Color.Green;
_lblSaveFileResult.Text = "Saved";
_lblSaveFileResult.Show();
}
catch (FormatException)
{
MessageBox.Show("The provided string was not valid Base64.", "Error", MessageBoxButtons.OK);
return;
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred while saving: {ex.Message}", "Error", MessageBoxButtons.OK);
_lblSaveFileResult.ForeColor = Color.Red;
_lblSaveFileResult.Text = "Error";
_lblSaveFileResult.Show();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Inventory.Data;
using Inventory.Models;
using Inventory.Services;
namespace Inventory.ViewModels
{
#region OrderStatusHistoryListArgs
public class OrderStatusHistoryListArgs
{
static public OrderStatusHistoryListArgs CreateEmpty() => new OrderStatusHistoryListArgs { IsEmpty = true };
public OrderStatusHistoryListArgs()
{
OrderBy = r => r.OrderLine;
}
public long OrderId { get; set; }
public bool IsEmpty { get; set; }
public string Query { get; set; }
public Expression<Func<OrderStatusHistory, object>> OrderBy { get; set; }
public Expression<Func<OrderStatusHistory, object>> OrderByDesc { get; set; }
}
#endregion
public class OrderStatusHistoryListViewModel : GenericListViewModel<OrderStatusHistoryModel>
{
private OrderStatusHistoryListArgs _viewModelArgs;
public OrderStatusHistoryListViewModel(IOrderStatusHistoryService orderStatusHistoryService, ICommonServices commonServices) : base(commonServices)
{
OrderStatusHistoryService = orderStatusHistoryService;
}
public IOrderStatusHistoryService OrderStatusHistoryService { get; }
public OrderStatusHistoryListArgs ViewModelArgs
{
get
{
if (_viewModelArgs == null)
_viewModelArgs = OrderStatusHistoryListArgs.CreateEmpty();
return _viewModelArgs;
}
private set => _viewModelArgs = value;
}
public async Task LoadAsync(OrderStatusHistoryListArgs args, bool silent = false)
{
ViewModelArgs = args ?? OrderStatusHistoryListArgs.CreateEmpty();
Query = ViewModelArgs.Query;
if (silent)
{
await RefreshAsync();
}
else
{
StartStatusMessage("Загружается история выполнения заказа...");
if (await RefreshAsync())
{
EndStatusMessage("История выполнения заказа загружена");
}
}
}
public void Unload()
{
ViewModelArgs.Query = Query;
}
public void Subscribe()
{
MessageService.Subscribe<OrderStatusHistoryListViewModel>(this, OnMessage);
MessageService.Subscribe<OrderStatusHistoryDetailsViewModel>(this, OnMessage);
//Подписываем OrderDetailsViewModel(доб. в историю при изм.статуса) на обр.сообщ. в OnMessage
MessageService.Subscribe<OrderDetailsViewModel>(this, OnMessage);
}
public void Unsubscribe()
{
MessageService.Unsubscribe(this);
}
public OrderStatusHistoryListArgs CreateArgs()
{
return new OrderStatusHistoryListArgs
{
Query = Query,
OrderBy = ViewModelArgs.OrderBy,
OrderByDesc = ViewModelArgs.OrderByDesc,
OrderId = ViewModelArgs.OrderId
};
}
public async Task<bool> RefreshAsync()
{
bool isOk = true;
Items = null;
ItemsCount = 0;
SelectedItem = null;
try
{
Items = await GetItemsAsync();
}
catch (Exception ex)
{
Items = new List<OrderStatusHistoryModel>();
StatusError($"Ошибка загрузки позиций заказа: {ex.Message}");
LogException("OrderStatusHistory", "Refresh", ex);
isOk = false;
}
ItemsCount = Items.Count;
if (!IsMultipleSelection)
{
SelectedItem = Items.FirstOrDefault();
}
NotifyPropertyChanged(nameof(Title));
return isOk;
}
private async Task<IList<OrderStatusHistoryModel>> GetItemsAsync()
{
if (!ViewModelArgs.IsEmpty)
{
DataRequest<OrderStatusHistory> request = BuildDataRequest();
return await OrderStatusHistoryService.GetOrderStatusHistorysAsync(request);
}
return new List<OrderStatusHistoryModel>();
}
private DataRequest<OrderStatusHistory> BuildDataRequest()
{
var request = new DataRequest<OrderStatusHistory>()
{
Query = Query,
OrderBy = ViewModelArgs.OrderBy,
OrderByDesc = ViewModelArgs.OrderByDesc
};
if (ViewModelArgs.OrderId > 0)
{
request.Where = (r) => r.OrderId == ViewModelArgs.OrderId;
}
return request;
}
protected override void OnDeleteSelection()
{
}
protected override void OnNew()
{
}
protected override async void OnRefresh()
{
StartStatusMessage("Loading order status history...");
if (await RefreshAsync())
{
EndStatusMessage("Order status history loaded");
}
}
private async void OnMessage(ViewModelBase sender, string message, object args)
{
switch (message)
{
case Messages.NewItemSaved:
case Messages.ItemDeleted:
case Messages.ItemsDeleted:
case Messages.ItemRangesDeleted:
await ContextService.RunAsync(async () =>
{
await RefreshAsync();
});
break;
}
}
private async void OnMessage(OrderDetailsViewModel sender, string message, object args)
{
switch (message)
{
case Messages.NewItemSaved:
case Messages.ItemDeleted:
case Messages.ItemChanged:
case Messages.ItemsDeleted:
case Messages.ItemRangesDeleted:
await ContextService.RunAsync(async () =>
{
await RefreshAsync();
});
break;
}
}
}
}
|
using UBaseline.Shared.QuotePanel;
using Uintra.Core.Search.Converters.SearchDocumentPanelConverter;
using Uintra.Core.Search.Entities;
using Uintra.Features.UintraPanels.ImagePanel.Models;
using Umbraco.Core;
namespace Uintra.Features.Search.Converters.Panel
{
public class ImagePanelSearchConverter : SearchDocumentPanelConverter<ImagePanelViewModel>
{
protected override SearchablePanel OnConvert(ImagePanelViewModel panel)
{
return new SearchablePanel
{
Title = panel.Title?.Value,
Content = panel.Description?.Value?.StripHtml()
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DevExpress.UserSkins;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
namespace DevReportDemo
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
DevExpress.UserSkins.BonusSkins.Register();
DevExpress.UserSkins.OfficeSkins.Register();
DevExpress.Skins.SkinManager.EnableFormSkins();
DevExpress.Skins.SkinManager.EnableMdiFormSkins();
BonusSkins.Register();
SkinManager.EnableFormSkins();
// UserLookAndFeel.Default.SetSkinStyle("DevExpress Dark Style");
//UserLookAndFeel.Default.SetSkinStyle("Office 2010 Blue");//皮肤主题
// | DevExpress Style | Caramel | Money Twins | DevExpress Dark Style| iMaginary
//| Lilian | Black | Blue | Office 2010 Blue | Office 2010 Black | Office 2010 Silver
// | Office 2007 Blue | Office 2007 Black | Officmetre 2007 Silver | Office 2007 Green
// | Office 2007 Pink | Seven | Seven Classic | Darkroom | McSkin | Sharp | Sharp Plus
// | Foggy | Dark Side | Xmas(Blue) | Springtime | Summer | Pumpkin | Valentine | Stardust
// | Coffee | Glass Oceans | High Contrast | Liquid Sky | London Liquid Sky| The Asphalt World| Blueprint |
Application.Run(new MainForm());
}
}
}
|
using System;
using Windows.UI.Xaml.Media.Imaging;
namespace ManillenWPhone.Models
{
public class Card : IComparable
{
public Suit Suit { get; set; }
public byte Number { get; set; }
public static Card BlankCard()
{
return new Card() { Number = 0 };
}
public BitmapImage Image
{
get
{
if (Number == 0) return null;
return new BitmapImage(new Uri("ms-appx:/Images/Cards/" + Number.ToString() + Suit.ToString() + ".png", UriKind.RelativeOrAbsolute));
}
}
public BitmapImage BackCardImage
{
get { return new BitmapImage(new Uri("ms-appx:/Images/Cards/CardsBack.jpg", UriKind.RelativeOrAbsolute)); }
}
public int CompareTo(object obj)
{
Card b = (Card)obj;
if (b.Suit > Suit)
return -1;
if (b.Suit < Suit)
return 1;
if (b.Number > Number)
return -1;
if (b.Number < Number)
return 1;
return 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mec.Model.Packs
{
public class BinDetailViewModel
{
public decimal ID { get; set; }
public string CODE { get; set; }
public string LOT_NO { get; set; }
public string INV_NO { get; set; }
public Nullable<decimal> I_NUM { get; set; }
public string WH_CODE { get; set; }
public string C_MATERIAL_NAME { get; set; }
public Nullable<DateTime> D_OPERATE { get; set; }
public string PartNumber { get; set; }
public string ProductCode { get; set; }
public bool IsSelected { get; set; }
}
}
|
using Alabo.App.Asset.Coupons.Domain.Entities;
using Alabo.Datas.UnitOfWorks;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.App.Asset.Coupons.Domain.Repositories
{
public class CouponRepository : RepositoryMongo<Coupon, ObjectId>, ICouponRepository
{
public CouponRepository(IUnitOfWork unitOfWork) : base(unitOfWork)
{
}
}
}
|
#if DEBUG
using Common.Business;
using Entity;
using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace Contracts.FCP
{
[ServiceContract(SessionMode = SessionMode.Required, Namespace = "http://www.noof.com/", Name = "FCP")]
public interface IFCPService
{
[OperationContract]
bool AddAMHistory(TrackBHistory data);
[OperationContract]
bool AddConformingProjectCompleteHistory(ConformingProjectCompleteHistory data);
[OperationContract]
bool AddDeleteFromLTO(int id);
[OperationContract]
bool AddDV01History(TrackDV01History data);
[OperationContract]
bool AddFCPHistory(TrackSHistory data);
[OperationContract]
bool AddItemToAMFixesScreen(int id);
[OperationContract]
bool AddMovieConformHistory(MovieConformHistory data);
[OperationContract]
bool AddToFailedAMQueue(int id);
[OperationContract]
bool AddQCHistory(TrackSQCHistory data);
[OperationContract]
bool AddUpdateAMRecord(TrackB data, bool isNew);
[OperationContract]
bool AddUpdateDV01Record(TrackDV01 data, bool isNew);
[OperationContract]
bool AddUpdateFCPRecord(TrackS data, bool isNew);
[OperationContract]
bool AddUpdateQCRecord(TrackSQC data, bool isNew);
[OperationContract]
bool CheckTitleOnAssetFailureExists(int id);
[OperationContract]
TrackSQC CheckTrackSQCRecordExists(int id, int itemNumber);
[OperationContract]
void CreateFCPMethods(string connectionString, string userName);
[OperationContract]
bool DeleteBSANTSData(int id, bool bsanOnly);
[OperationContract]
TrackB GetAirMaster(int id);
[OperationContract]
int GetAlternateHDId(int id);
[OperationContract]
int GetAlternateSDHDId(int id);
[OperationContract]
int GetAlternateSDId(int id);
[OperationContract]
Tuple<int, string, int?> GetAltIdRuntime(int id);
[OperationContract]
Tuple<string, string, string> GetAMRuntimes(int id);
[OperationContract]
string GetBroadcastTitle(int id);
[OperationContract]
int? GetClipCompId(string aka1, string type);
[OperationContract]
string[] GetConformingDirectories();
[OperationContract]
ConformingProjectComplete GetConformingProjectComplete(int masterId);
[OperationContract]
TrackDV01 GetDV01Record(int id);
[OperationContract]
TrackS GetFCP(int id);
[OperationContract]
TrackSHistory GetFCPHistoryRecord(int id);
[OperationContract]
List<string> GetFCPLocations();
[OperationContract]
string GetFCPProjectLocation(int id);
[OperationContract]
List<string> GetFCPStatuses();
[OperationContract]
int GetHistoryId(int id);
[OperationContract]
int GetMasterId(int id);
[OperationContract]
int GetMarkedAsFailedCount(int id);
[OperationContract]
MovieConform GetMovieConform(int id);
[OperationContract]
Tuple<int?, int?, string> GetMovieDefinitionRatingType(int id);
[OperationContract]
Tuple<int, string, string> GetMovieRatingContractTitleType(int id);
[OperationContract]
Tuple<string, int> GetMovieTitleRating(int id);
[OperationContract]
string GetMovieType(int id);
[OperationContract]
Tuple<string, int> GetMovieTypeRating(int id);
[OperationContract]
string GetNAD(int id);
[OperationContract]
string GetNAD33(int id, string type, DateTime date, string channelType);
[OperationContract]
Tuple<int, int, string> GetNADInfo(int id);
[OperationContract]
HistoryInfo GetNOCQC(int id);
[OperationContract]
int GetNOCUnderReviewCount(int id);
[OperationContract]
int GetOtherVersionId(int masterId, bool isHD, string type, int rating);
[OperationContract]
HistoryInfo GetPassedQC(int id);
[OperationContract]
List<TrackSQC> GetQCData(int id);
[OperationContract]
HistoryInfo GetQCDateUser(int id);
[OperationContract]
string GetRating(int id);
[OperationContract]
Tuple<int, int> GetRatingAndGay(int id);
[OperationContract]
string GetRatingText(int xxx);
[OperationContract]
string GetReasonText(string contentType);
[OperationContract]
Tuple<string, string, string> GetRuntimes(int id);
[OperationContract]
int GetTrackSFailCount(int id);
[OperationContract]
string GetTrackSStatus(int id);
[OperationContract]
int GetTVMACount(int id);
[OperationContract]
int GetXXX(int id);
[OperationContract]
bool HasAirMaster(int id);
[OperationContract]
bool HasBRecord(int id);
[OperationContract]
bool HasSDData(int id);
[OperationContract]
bool IsAlreadySaved(int id, int itemId);
[OperationContract]
bool IsHD(int id);
[OperationContract]
bool UpdateAMRuntimes(int id, string som, string eom, string trt, string userName);
[OperationContract]
bool UpdateConformingProjectCompleteRecord(ConformingProjectComplete data);
[OperationContract]
bool UpdateMovieConformRecord(MovieConform data);
[OperationContract]
bool UpdateMovieInfoRuntime(int id, string runtime, int ckRuntime);
[OperationContract]
bool UpdateTRT(int id, string trt);
[OperationContract]
bool UseTitleOnAsset();
}
}
#endif
|
using C1.Win.C1FlexGrid;
using Clients.Conforming;
using Common;
using Common.Extensions;
using Common.Log;
using Common.Presentation;
using SessionSettings;
using System;
using System.Data;
using System.Drawing;
using System.ServiceModel;
using System.Threading;
using System.Windows.Forms;
namespace Conforming.Modals
{
public partial class SpanishQCDerivatives : SkinnableModalBase
{
#region Private Fields
private ClientPresentation mClientPresentation = new ClientPresentation();
private string mConnectionString = String.Empty;
private int mIsHD = 0;
private int mOriginalId = 0;
private ConformingProxy mProxy = null;
private string mUserName = String.Empty;
#endregion
#region Constructors
public SpanishQCDerivatives(ParameterStruct parameters, SkinnableFormBase owner, int hd, int id)
: base(parameters, owner)
{
InitializeComponent();
ApplySkin(parameters);
SetCaption("Spanish QC Required - Derivatives");
owner.AddOwnedForm(this);
Logging.ConnectionString = mConnectionString = Settings.ConnectionString;
mUserName = Settings.UserName;
mIsHD = hd;
mOriginalId = id;
}
#endregion
#region Protected Methods
protected override void DoOK()
{
if (UpdateQCStatus())
base.DoOK();
else
base.DoCancel();
}
#endregion
#region Private Methods
private void Cancel_Click(object sender, EventArgs e)
{
mProxy = null;
DoCancel();
}
private void CloseProxy()
{
if (mProxy != null && mProxy.State != CommunicationState.Closed && mProxy.State != CommunicationState.Faulted)
{
Thread.Sleep(30);
mProxy.Close();
}
mProxy = null;
}
private void LoadData()
{
Cursor = Cursors.AppStarting;
OpenProxy();
qcGrid.BeginUpdate();
qcGrid.Rows.Count = 1;
qcGrid.Redraw = false;
qcGrid.AutoResize = false;
try
{
int? derivativeId = mProxy.GetDerivativeId(mOriginalId);
if (!derivativeId.HasValue)
return;
using (DataTable table = mProxy.GetSpanishDerivatives(derivativeId.Value, mOriginalId, mIsHD))
{
if (table.HasRows())
{
foreach (DataRow dr in table.Rows)
{
Row row = qcGrid.Rows.Add();
qcGrid.SetData(row.Index, 0, Convert.ToInt32(dr["id"]));
qcGrid.SetData(row.Index, 1, dr["title"].ToString());
string rating = mProxy.GetXXX(Convert.ToInt32(dr["Rating"]));
qcGrid.SetData(row.Index, 2, rating);
qcGrid.SetData(row.Index, 3, Convert.ToBoolean(Convert.ToInt32(dr["spanish_qc"])));
}
for (int i = 0; i < 3; i++)
{
qcGrid.Cols[i].AllowEditing = false;
}
}
}
}
catch (Exception e)
{
Logging.Log(e, "Conforming", "SpanishQCDerivatives.LoadData");
mClientPresentation.ShowError(e.Message + "\n" + e.StackTrace);
}
finally
{
Cursor = Cursors.Default;
qcGrid.Redraw = true;
qcGrid.AutoResize = true;
qcGrid.EndUpdate();
CloseProxy();
}
}
private void OK_Click(object sender, EventArgs e)
{
mProxy = null;
DoOK();
}
/// <summary>
/// Creates the synchronous proxy.
/// </summary>
private void OpenProxy()
{
if (mProxy == null || mProxy.State == CommunicationState.Closed)
{
mProxy = new ConformingProxy(Settings.Endpoints["Conforming"]);
mProxy.Open();
mProxy.CreateConformingMethods(mConnectionString, mUserName);
}
}
private void SetUpForm()
{
ok.Location = new Point(593, 112);
cancel.Location = new Point(593, 170);
}
private void SpanishQCDerivatives_Load(object sender, EventArgs e)
{
SetUpForm();
LoadData();
}
private bool UpdateQCStatus()
{
bool result = true;
OpenProxy();
try
{
for (int i = 1; i < qcGrid.Rows.Count; i++)
{
int id = Convert.ToInt32(qcGrid.GetData(i, 0));
int qc = 0;
if (qcGrid.GetCellCheck(i, 3) == CheckEnum.Checked)
qc = 1;
result &= mProxy.UpdateSpanishQC(id, qc);
}
}
catch (Exception e)
{
Logging.Log(e, "Conforming", "SpanishQCDerivatives.UpdateQCStatus");
mClientPresentation.ShowError(e.Message + "\n" + e.StackTrace);
}
finally
{
CloseProxy();
}
return result;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BELCORP.GestorDocumental.BE.Comun;
using System.IO;
namespace BELCORP.GestorDocumental.BE.DDP
{
public class DocumentoDDPBE
{
public int ID { get; set; }
public string CodigoDocumento { get; set; }
public string BibliotecaNombre { get; set; }
public string BibliotecaGuid { get; set; }
public UsuarioBE Elaborador { get; set; }
public string Estado { get; set; }
public TipoDocumentalBE TipoDocumental { get; set; }
public UsuarioBE Revisor { get; set; }
public string SistemaCalidad { get; set; }
public string UrlDocumentoRelativaSitio { get; set; }
public string UrlDocumento { get; set; }
public string UrlDocumento_CNC { get; set; }
public string UrlDocumento_CC { get; set; }
public string UrlDocumento_ORG { get; set; }
public string NombreDocumento { get; set; }
public string Extension { get; set; }
public string URLDispForm { get; set; }
public string RutaOfficeWebApp { get; set; }
public UsuarioBE Aprobador { get; set; }
public bool Eliminado { get; set; }
public bool Sincronizado { get; set; }
public List<UsuarioBE> SubAdministradores { get; set; }
public List<PerfilesBE> UsuariosNotificarEnPublicacionA { get; set; }
#region Demás Campos
public int Version { get; set; }
public string Titulo { get; set; }
public DateTime FechaRegistro { get; set; }
public DateTime FechaPublicacion { get; set; }
public DateTime FechaCaducidad { get; set; }
public ElementoBE AcuerdoNivelesServicio { get; set; }
public string AreaElaborador { get; set; }
public int AreaPrincipalID { get; set; }
public int SubAreaID { get; set; }
public string ClasificacionDocumentos { get; set; }
public string CodigoUCM { get; set; }
public string Comentario { get; set; }
public List<CompaniaBE> PaisCompanias { get; set; }
public List<SubAreaBE> AreaSubAreas { get; set; }
public UsuarioBE Contribuidor { get; set; }
public int Corporativo { get; set; }
public ElementoBE DescripcionProcesos { get; set; }
public int DistribucionFisica { get; set; }
public DateTime FechaUltimaAprobacion { get; set; }
public GrupoSeguridadBE GrupoSeguridad { get; set; }
public ElementoBE Instruccion { get; set; }
public MacroProcesoBE MacroProceso { get; set; }
public ElementoBE ManualCalidad { get; set; }
public MetodoAnalisisPrincipalBE MetodoAnalisisPrincipal { get; set; }
public ElementoBE MetodoAnalisis { get; set; }
public ElementoBE MetodoAnalisisExterno { get; set; }
public string ModificandosePor { get; set; }
public int NotificacionCorporativa { get; set; }
public List<CentroCostoBE> NotificarEnPublicacionA { get; set; }
public ElementoBE PlanMaestro { get; set; }
public ElementoBE Politica { get; set; }
public ElementoBE PoliticaCalidad { get; set; }
public ElementoBE Procedimiento { get; set; }
public ProcesoBE Proceso { get; set; }
public TipoPlanMaestroBE TipoPlanMaestro { get; set; }
public byte[] Archivo { get; set; }
//public Stream ArchivoStream { get; set; }
public List<UsuarioBE> LectoresNoPublicos { get; set; }
public string AreaPrincipal { get; set; }
public string SubArea { get; set; }
#endregion
public UsuarioBE BloqueadoVCPara { get; set; }
public UsuarioBE BloqueadoPubPara { get; set; }
public String RevisoresPM { get; set; }
public string CodigoTipo { get; set; }
public DocumentoDDPBE()
{
TipoDocumental = new TipoDocumentalBE();
PaisCompanias = new List<CompaniaBE>();
AreaSubAreas = new List<SubAreaBE>();
Contribuidor = new UsuarioBE();
GrupoSeguridad = new GrupoSeguridadBE();
MacroProceso = new MacroProcesoBE();
MetodoAnalisisPrincipal = new MetodoAnalisisPrincipalBE();
NotificarEnPublicacionA = new List<CentroCostoBE>();
Proceso = new ProcesoBE();
TipoPlanMaestro = new TipoPlanMaestroBE();
AcuerdoNivelesServicio = new ElementoBE();
DescripcionProcesos = new ElementoBE();
Instruccion = new ElementoBE();
ManualCalidad = new ElementoBE();
MetodoAnalisis = new ElementoBE();
MetodoAnalisisExterno = new ElementoBE();
PlanMaestro = new ElementoBE();
Politica = new ElementoBE();
PoliticaCalidad = new ElementoBE();
Procedimiento = new ElementoBE();
Revisor = new UsuarioBE();
SubAdministradores = new List<UsuarioBE>();
Revisor = new UsuarioBE();
Elaborador = new UsuarioBE();
Aprobador = new UsuarioBE();
LectoresNoPublicos = new List<UsuarioBE>();
UsuariosNotificarEnPublicacionA = new List<PerfilesBE>();
BloqueadoPubPara = new UsuarioBE();
BloqueadoVCPara = new UsuarioBE();
}
}
}
|
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Validation;
using Teste_CRUD_CiaTecnica.Domain.Entities;
using Teste_CRUD_CiaTecnica.Infra.Data.EntityConfig;
namespace Teste_CRUD_CiaTecnica.Infra.Data.Context
{
public class DBContext_Teste_CRUD : DbContext, IDisposable
{
public DbSet<Pessoa> Pessoa { get; set; }
public DbSet<PessoaFisica> PessoaFisica { get; set; }
public DbSet<PessoaJuridica> PessoaJuridica { get; set; }
public DBContext_Teste_CRUD()
:base("OracleDbContext") //DB_Teste_CRUD
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("SYSTEM");
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
modelBuilder.Configurations.Add(new PessoaConfiguration());
modelBuilder.Configurations.Add(new PessoaFisicaConfiguration());
modelBuilder.Configurations.Add(new PessoaJuridicaConfiguration());
modelBuilder.Properties<string>()
.Configure(p => p.HasColumnType("varchar2"));
modelBuilder.Properties<string>()
.Configure(p => p.HasMaxLength(100));
}
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException e)
{
var erro = "Entidade do tipo {0} em estado de {1} possui os seguintes erros de validação: ";
foreach (var eve in e.EntityValidationErrors)
{
erro = String.Format(erro, eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
erro += String.Format("Propriedade: {0} - Erro: {1}", ve.PropertyName, ve.ErrorMessage);
}
}
throw new Exception(erro);
}
}
}
}
|
using GameOfGame.Controls.CustomCell;
using System.Windows;
using System.Windows.Controls;
using GameOfGame.Utils;
using System.Collections.Generic;
namespace GameOfGame.Controls.CustomGrid
{
public partial class TableGrid : UserControl
{
private TableCell[,] grid = new TableCell[3,3];
private List<TableCell> listGrid = new List<TableCell>();
public TableCell[,] Grid
{
get
{
return this.grid;
}
}
private void fillGrid()
{
int i = 0, j = 0;
foreach (TableCell tc in U.CopiiPatriei<TableCell>(this.GameTable))
{
if (j == 3)
{
j = 0;
i++;
}
this.grid[i, j] = tc;
this.listGrid.Add(tc);
j++;
}
}
public TableGrid()
{
InitializeComponent();
this.fillGrid();
}
public RoutedEventHandler OnTableClick;
private void TableGridClick(object sender, RoutedEventArgs e)
{
if (this.OnTableClick is null)
return;
this.OnTableClick(sender, e);
}
public void Reset()
{
foreach(TableCell tc in this.listGrid)
{
tc.Type = CellType.NullType;
}
}
private int checkLine(int l)
{
int s = 0;
for (int i = 0; i < 2; i++)
{
if (this.grid[l, i].Type == this.grid[l, i + 1].Type)
s++;
}
if (s == 2)
return (int)this.grid[l, l].Type;
return -1;
}
private int checkCol(int c)
{
int s = 0;
for (int i = 0; i < 2; i++)
{
if (this.grid[i, c].Type == this.grid[i + 1, c].Type)
s++;
}
if (s == 2)
return (int)this.grid[c, c].Type;
return -1;
}
private int checkPDiag()
{
int s = 0;
for(int i = 0; i < 2; i++)
{
if (this.grid[i, i].Type == this.grid[i + 1, i + 1].Type)
s++;
}
if (s == 2)
return (int)this.grid[1, 1].Type;
return -1;
}
private int checkSDiag()
{
int s = 0;
if (this.grid[0, 2].Type == this.grid[1, 1].Type)
s++;
if (this.grid[1, 1].Type == this.grid[2, 0].Type)
s++;
if (s == 2)
return (int)this.grid[1, 1].Type;
return -1;
}
public bool isFull()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (this.grid[i, j].Type == CellType.NullType)
return false;
}
}
return true;
}
public int Check()
{
for (int l = 0; l < 3; l++)
{
if (checkLine(l) == 1 || checkLine(l) == 2)
return checkLine(l);
}
for (int c = 0; c < 3; c++)
{
if (checkCol(c) == 1 || checkCol(c) == 2)
return checkCol(c);
}
if (checkPDiag() == 1 || checkPDiag() == 2)
return checkPDiag();
if (checkSDiag() == 1 || checkSDiag() == 2)
return checkSDiag();
if (isFull())
return -1;
return 0;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZM.TiledScreenDesigner
{
public class BorderTypeConverter : TypeConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
var b = value as Border;
return string.Format("{0}px, op. {1}", b?.Width, b?.Opacity);
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
return TypeDescriptor.GetProperties(typeof(Border), attributes);
}
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
}
}
}
|
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Claudia.SoundCloud.EndPoints
{
public class Pagenation<T>
{
[JsonProperty("collection")]
public List<T> Collection { get; private set; }
[JsonProperty("next_href")]
public string NextHref { get; private set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MenuHandlerScript : MonoBehaviour
{
public void sound_volume(float volume)
{
PlayerPrefs.SetFloat("volume", volume);
}
private bool isClosed = true;
[SerializeField]Animator anim;
public void startPressed(){
SceneManager.LoadScene("ScanScene");
}
public void inmenuPressed(GameObject _toPanel){
_toPanel.SetActive(true);
}
public void backtoMenu(GameObject _currentPanel){
_currentPanel.SetActive(false);
}
public void quitPressed(){
Application.Quit();
}
public AudioSource musik, touch;
public Slider volume_musik, volume_effect;
void OnMouseDown()
{
touch.volume = volume_effect.value;
musik.volume = volume_musik.value;
}
public void menuPressed(){
if(isClosed == true){
anim.SetTrigger("Open");
isClosed = false;
}else{
anim.SetTrigger("Close");
isClosed = true;
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.ContentItemVersions;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Contexts;
using DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces.Results.AllowSync;
using DFC.ServiceTaxonomy.GraphSync.Services;
using OrchardCore.ContentManagement;
namespace DFC.ServiceTaxonomy.GraphSync.GraphSyncers.Interfaces
{
//todo: rename? as deletes and unpublishes
public interface IDeleteGraphSyncer
{
string? GraphReplicaSetName { get; }
Task<IAllowSync> DeleteAllowed(
ContentItem contentItem,
IContentItemVersion contentItemVersion,
SyncOperation syncOperation,
IEnumerable<KeyValuePair<string, object>>? deleteIncomingRelationshipsProperties = null,
IGraphDeleteContext? parentContext = null);
Task<IAllowSync> DeleteIfAllowed(
ContentItem contentItem,
IContentItemVersion contentItemVersion,
SyncOperation syncOperation,
IEnumerable<KeyValuePair<string, object>>? deleteIncomingRelationshipsProperties = null);
Task Delete(SyncOperation syncOperation);
Task DeleteEmbedded(ContentItem contentItem);
}
}
|
using DAL.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Interfaces
{
public interface IBankAccountRepository : IRepository<UserBankAccount>
{
UserBankAccount GetBankAccount(string userId, string bankName);
IQueryable<UserBankAccount> GetUserBankAccounts(string userId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using evrostroy.Domain.Interfaces;
namespace evrostroy.Domain
{
public class DataManager
{//в этом классе ценрализовано происходит обмен данными
//этот класс будем внедрять в конструктор каждого контроллера
private IUsersRepository usersRepository;
private IProductsRepository productsRepository;
public DataManager(IUsersRepository usersRepository, IProductsRepository productsRepository)
{
this.usersRepository = usersRepository;
this.productsRepository = productsRepository;
}
//объявим свойства через которые будем возвращать репозитории требуемые для работы
public IUsersRepository UsersRepository
{
get { return usersRepository; }
}
public IProductsRepository ProductsRepository
{
get { return productsRepository; }
}
}
}
|
using BassClefStudio.GameModel.Graphics.Commands.Turtle;
using BassClefStudio.NET.Core.Primitives;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace BassClefStudio.GameModel
{
internal static class SKExtensions
{
public static SKColor ToSkia(this Color color)
{
return new SKColor(color.R, color.G, color.B, color.A);
}
public static SKStrokeCap ToSkia(this LineCap cap)
{
if (cap == LineCap.Flat)
{
return SKStrokeCap.Butt;
}
else if (cap == LineCap.Round)
{
return SKStrokeCap.Round;
}
else if (cap == LineCap.Square)
{
return SKStrokeCap.Square;
}
else
{
throw new ArgumentException($"Unknown pen type: {cap}.", "cap");
}
}
public static SKPoint ToSkia(this Vector2 vector)
{
return new SKPoint(vector.X, vector.Y);
}
public static SKPaintStyle ToSkia(this FillMode fill)
{
if (fill == FillMode.Outline)
{
return SKPaintStyle.Stroke;
}
else if (fill == FillMode.Fill)
{
return SKPaintStyle.Fill;
}
else if (fill == FillMode.Both)
{
return SKPaintStyle.StrokeAndFill;
}
else
{
throw new ArgumentException($"Unknown fill type: {fill}.", "fill");
}
}
}
}
|
using Rg.Plugins.Popup.Pages;
namespace RRExpress.Seller.Views {
public partial class ChannelView : PopupPage {
public ChannelView() {
InitializeComponent();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplicationBlog_DejanSavanovic.Models
{
public class BlogDetailsViewModel
{
public int BlogId { get; set; }
public string Autor { get; set; }
public string Drzava { get; set; }
public string Naslov { get; set; }
public string Sadrzaj { get; set; }
public Nullable<System.DateTime> DatumPutovanja { get; set; }
public string NaslovnaSlikaLink { get; set; }
public System.DateTime DatumKreiranja { get; set; }
public bool DozvolaDodavanjaSlika { get; set; }
public bool DaLiMiSeSvidjaBlog { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using com.Sconit.Service;
using Telerik.Web.Mvc;
using com.Sconit.Utility;
using com.Sconit.Web.Models;
using com.Sconit.Entity.INV;
using com.Sconit.Web.Models.SearchModels.INV;
using com.Sconit.Entity.Exception;
namespace com.Sconit.Web.Controllers.INV
{
public class InventoryFreezeController : WebAppBaseController
{
#region Properties
//public IGenericMgr genericMgr { get; set; }
public ILocationDetailMgr LocDetGeneMgr { get; set; }
//public IItemMgr itemMgr { get; set; }
//
// GET: /LocationTransaction/
#endregion
private static string selectCountStatement = "select count(*) from LocationLotDetail as l";
private static string selectStatement = "from LocationLotDetail as l";
#region public
public ActionResult Index()
{
return View();
}
/// <summary>
/// List action
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel"> LocationLotDetail Search model</param>
/// <returns>return the result view</returns>
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_Inventory_InventoryFreeze_View")]
public ActionResult List(GridCommand command, LocationLotDetailSearchModel searchModel)
{
if (!string.IsNullOrEmpty(searchModel.Location))
{
TempData["_AjaxMessage"] = "";
}
else
{
SaveWarningMessage(Resources.EXT.ControllerLan.Con_LocationSearchConditionCanNotBeEmpty);
}
TempData["LocationLotDetailSearchModel"] = searchModel;
return View();
}
/// <summary>
/// AjaxList action
/// </summary>
/// <param name="command">Telerik GridCommand</param>
/// <param name="searchModel"> LocationLotDetail Search Model</param>
/// <returns>return the result action</returns>
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_Inventory_InventoryFreeze_View")]
public ActionResult _AjaxList(GridCommand command, LocationLotDetailSearchModel searchModel)
{
if (string.IsNullOrEmpty(searchModel.Location))
{
return PartialView(new GridModel(new List<LocationLotDetail>()));
}
SearchStatementModel searchStatementModel = this.PrepareSearchStatement(command, searchModel);
var list = GetAjaxPageData<LocationLotDetail>(searchStatementModel, command);
foreach (var data in list.Data)
{
data.ItemDescription = itemMgr.GetCacheItem(data.Item).Deriction;
}
return PartialView(GetAjaxPageData<LocationLotDetail>(searchStatementModel, command));
}
[SconitAuthorize(Permissions = "Url_Inventory_InventoryFreeze_Freeze,Url_Inventory_InventoryFreeze_UnFreeze")]
public ActionResult PopFreeze(Boolean IsFreeze)
{
ViewBag.IsFreeze = IsFreeze;
return PartialView();
}
[SconitAuthorize(Permissions = "Url_Inventory_InventoryFreeze_Freeze")]
public JsonResult _Freeze(string item, string location, string lotNo, string manufactureParty)
{
try
{
if (item == null || item == "")
{
throw new BusinessException(Resources.EXT.ControllerLan.Con_ItemCanNotBeEmpty);
}
if (location == null || location == "")
{
throw new BusinessException(Resources.EXT.ControllerLan.Con_LocationCanNotBeEmpty);
}
if (lotNo == null || lotNo == "")
{
throw new BusinessException(Resources.EXT.ControllerLan.Con_BatchNumberCanNotBeEmpty);
}
LocDetGeneMgr.InventoryFreeze(item, location, lotNo, manufactureParty);
object obj = new { SuccessMessage = string.Format(Resources.INV.LocationLotDetail.LocationLotDetail_Freezed, item) };
return Json(obj);
}
catch (BusinessException ex)
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 500;
Response.Write(ex.GetMessages()[0].GetMessageString());
return Json(null);
}
}
[SconitAuthorize(Permissions = "Url_Inventory_InventoryFreeze_UnFreeze")]
public JsonResult _UnFreeze(string item, string location, string lotNo, string manufactureParty)
{
try
{
if (item == null || item == "")
{
throw new BusinessException(Resources.EXT.ControllerLan.Con_ItemCanNotBeEmpty);
}
if (location == null || location == "")
{
throw new BusinessException(Resources.EXT.ControllerLan.Con_LocationCanNotBeEmpty);
}
if (lotNo == null || lotNo == "")
{
throw new BusinessException(Resources.EXT.ControllerLan.Con_BatchNumberCanNotBeEmpty);
}
LocDetGeneMgr.InventoryUnFreeze(item, location, lotNo, manufactureParty);
object obj = new { SuccessMessage = string.Format(Resources.INV.LocationLotDetail.LocationLotDetail_UnFreezed, item) };
return Json(obj);
}
catch (BusinessException ex)
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 500;
Response.Write(ex.GetMessages()[0].GetMessageString());
return Json(null);
}
}
#endregion
#region private
private SearchStatementModel PrepareSearchStatement(GridCommand command, LocationLotDetailSearchModel searchModel)
{
string whereStatement = " where HuId is not null";
IList<object> param = new List<object>();
SecurityHelper.AddLocationPermissionStatement(ref whereStatement, "l", "Location");
HqlStatementHelper.AddEqStatement("Item", searchModel.Item, "l", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("LotNo", searchModel.LotNo, "l", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Location", searchModel.Location, "l", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("ManufactureParty", searchModel.ManufactureParty, "l", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("IsFreeze", searchModel.IsFreeze, "l", ref whereStatement, param);
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
#endregion
}
}
|
using A4CoreBlog.Data.Common.Repositories;
using A4CoreBlog.Data.Models;
using System.Threading.Tasks;
namespace A4CoreBlog.Data.UnitOfWork
{
public interface IBlogSystemData
{
IRepository<User> Users { get; }
IRepository<Blog> Blogs { get; }
IRepository<BlogComment> BlogComments { get; }
IRepository<Post> Posts { get; }
IRepository<PostComment> PostComments { get; }
IRepository<Comment> Comments { get; }
IRepository<SystemImage> Images { get; }
int SaveChanges();
Task<int> SaveChangesAsync();
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TryCubemap : MonoBehaviour {
public ReflectionProbe rp;
public Camera cenCam;
public Cubemap testCubemap;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.H)) {
rp.RenderProbe();
this.GetComponent<Renderer>().material.SetTexture("_Cube", rp.bakedTexture);
print(rp.bakedTexture.name);
cenCam.RenderToCubemap(testCubemap);
}
}
}
|
using System;
using UnityEngine;
enum CameraState
{
FIRST_MOVE, MOVING, IDLE, DISABLED
}
public class MainGameCamera : MonoBehaviour
{
public static MainGameCamera Instance { get; private set; } = null;
public Transform target;
public float movementSpeed;
public float rotationSpeed;
public float scaleSpeed;
public Transform [] boards;
bool SaveAngleAndPosition {
get { return Settings.Instance.SaveAngleAndPositionOnBoardChange; }
}
bool RotateOnChangePlayer {
get { return Settings.Instance.RotateCameraOnChangePlayer; }
}
Vector3 dest;
GameManager _gameManager;
CameraState _state;
CameraState State {
get { return _state; }
set {
switch (value) {
case CameraState.FIRST_MOVE: {
_gameManager.IsAnimated = true;
dest = target.position + ((_activePlayer == Color.WHITE) ? new Vector3 (0, 7, -5) : new Vector3 (0, 7, 5));
break;
}
case CameraState.MOVING: {
_gameManager.IsAnimated = true;
Transform tr = GetComponent<Transform> ();
if (SaveAngleAndPosition) {
float ver = -100f;
if (tr.position.y <= 0)
ver = tr.position.y + 7f;
else if (tr.position.y <= 10)
ver = tr.position.y - 3f;
else
ver = tr.position.y - 13f;
//dest = new Vector3 (tr.position.x, target.position.y + 3f, tr.position.z);
dest = new Vector3 (tr.position.x, target.position.y + ver + 3f, tr.position.z);
} else {
dest = target.position + ((_activePlayer == Color.WHITE) ? new Vector3 (0, 7, -5) : new Vector3 (0, 7, 5));
}
break;
}
case CameraState.DISABLED:
break;
default: {
_gameManager.IsAnimated = false;
break;
}
}
_state = value;
}
}
Color _activePlayer;
void Awake () {
if (Instance != null)
throw new DragonChessException ("Game manager awakened, but it's Instance is already set");
Instance = this;
}
void Start () {
if (target == null)
State = CameraState.DISABLED;
if (Input.touchSupported)
gameObject.AddComponent<CameraTouchInputController> ();
gameObject.AddComponent<CameraKeyboardInputController> ();
}
public void Init (Transform [] newBoards, int initBoard = 0)
{
_gameManager = GameObject.FindGameObjectWithTag ("GameController").GetComponent<GameManager> ();
_activePlayer = _gameManager.ActivePlayerColor;
boards = newBoards;
if (initBoard > 0 && initBoard < boards.Length) {
target = boards [initBoard];
} else {
target = boards [0];
}
State = CameraState.FIRST_MOVE;
}
void Update ()
{
switch (State) {
case CameraState.FIRST_MOVE: {
Transform tr = GetComponent<Transform> ();
tr.position = Vector3.Lerp (tr.position, dest, 0.05f * 60f * Time.deltaTime);
if (target.position.y < tr.position.y)
tr.rotation = Quaternion.Slerp (tr.rotation, Quaternion.LookRotation (target.position - tr.position), 0.2f);
if (Vector3.Distance (tr.position, dest) < .05f) {
tr.position = dest;
tr.LookAt (target);
_gameManager.IsAnimated = false;
State = CameraState.IDLE;
}
break;
}
case CameraState.MOVING: {
Transform tr = GetComponent<Transform> ();
tr.position = Vector3.Lerp (tr.position, dest, 0.05f * 60f * Time.deltaTime);
if (!SaveAngleAndPosition && target.position.y < tr.position.y)
tr.rotation = Quaternion.Slerp (tr.rotation, Quaternion.LookRotation (target.position - tr.position), 0.2f);
if (Vector3.Distance (tr.position, dest) < .05f) {
tr.position = dest;
if (!SaveAngleAndPosition)
tr.LookAt (target);
_gameManager.IsAnimated = false;
State = CameraState.IDLE;
}
break;
}
}
if (RotateOnChangePlayer && _activePlayer != _gameManager.ActivePlayerColor && _state != CameraState.DISABLED) {
_activePlayer = _gameManager.ActivePlayerColor;
State = CameraState.MOVING;
}
}
public void GoToBoard (int board)
{
if (board < 0 || board >= boards.Length)
//return;
throw new IndexOutOfRangeException ("Board number is out of bounds");
target = boards [board];
State = CameraState.MOVING;
}
public void GoUp ()
{
for (int i = 0; i < boards.Length; i++) {
if (target == boards [i]) {
if (i != boards.Length - 1) {
target = boards [i + 1];
State = CameraState.MOVING;
}
break;
}
}
}
public void GoDown ()
{
for (int i = 0; i < boards.Length; i++) {
if (target == boards [i]) {
if (i != 0) {
target = boards [i - 1];
State = CameraState.MOVING;
}
break;
}
}
}
public void Disable ()
{
State = CameraState.DISABLED;
}
public void Move (Vector2 pos)
{
pos *= 30f * Time.deltaTime;
if (State == CameraState.IDLE) {
var tr = GetComponent<Transform> ();
tr.Rotate (new Vector3 (-60, 0));
tr.Translate (new Vector3 (pos.x, 0, pos.y), Space.Self);
tr.Rotate (new Vector3 (60, 0));
CheckBoundaries ();
}
}
public void Zoom (float scale)
{
scale *= 30f * Time.deltaTime;
if (State == CameraState.IDLE) {
var tr = GetComponent<Transform> ();
if (scale > 0f) {
if (tr.position.y > 3f + target.position.y) {
tr.Translate (Vector3.forward * scale);
}
} else {
if (tr.position.y < 10f + target.position.y) {
tr.Translate (Vector3.forward * scale);
}
}
CheckBoundaries ();
}
}
public void Rotate (float degree)
{
degree *= 30f * Time.deltaTime;
if (State == CameraState.IDLE) {
var tr = GetComponent<Transform> ();
tr.RotateAround (target.position, target.up, degree);
CheckBoundaries ();
}
}
public void Rotate (bool clockwise)
{
if (State == CameraState.IDLE) {
var tr = GetComponent<Transform> ();
tr.RotateAround (target.position, target.up, clockwise ? rotationSpeed : -rotationSpeed);
CheckBoundaries ();
}
}
public void ResetPosition ()
{
State = CameraState.MOVING;
}
void CheckBoundaries ()
{
var tr = GetComponent<Transform> ();
float x = tr.position.x;
float y = tr.position.y;
float z = tr.position.z;
if (x < target.position.x - 10f)
x = target.position.x - 10f;
else if (x > target.position.x + 10f)
x = target.position.x + 10f;
if (y < target.position.y + 3f)
y = target.position.y + 3f;
else if (y > target.position.y + 10f)
y = target.position.y + 10f;
if (z < target.position.z - 10f)
z = target.position.z - 10f;
else if (z > target.position.z + 10f)
z = target.position.z + 10f;
tr.position = new Vector3 (x, y, z);
}
}
|
using System;
using System.Threading.Tasks;
using AutoMapper.QueryableExtensions;
using DataAccess.Users;
using Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using ViewModel.Users;
namespace DataAccess.DbImplementation.Users
{
public class UserQuery : IUserQuery
{
private readonly UserManager<User> _userManager;
public UserQuery(UserManager<User> userManager)
{
_userManager = userManager;
}
public async Task<UserResponse> RunAsync(Guid userId)
{
UserResponse response = await _userManager.Users.Include("Recipies")
.Include("Recipies")
.Include("Reviews")
.Include("CheapPlaces")
.Include("RateReviews")
.Include("RateCheapPlaces")
.ProjectTo<UserResponse>()
.FirstOrDefaultAsync(p => p.Id == userId);
return response;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Collections;
using SKYPE4COMLib;
using System.Timers;
namespace SoundServant
{
public class Listener
{
string name;
bool participateByDefault;
public readonly int Id;
string contact;
bool inCall = false;
ListenerState state = ListenerState.Disconnected;
DateTime timeCallStartedAt;
TimeSpan finishedCallDuration;
Congregation congregation;
Call callHandle;
TCallStatus callStatus = TCallStatus.clsUnknown;
public Call CallHandle { get { return callHandle; } }
public TCallStatus CallStatus { get { return callStatus; } }
public int CallId { get { return callHandle.Id; } }
public TimeSpan CallDuration
{
get
{
if (state == ListenerState.InCall)
{
return new TimeSpan(0, 0, callHandle.Duration);
}
else if (callStatus == TCallStatus.clsFinished)
return finishedCallDuration;
else
return new TimeSpan(0, 0, 0);
}
}
public string Name { get { return name; } set { name = value; Update(); } }
public bool ParticipateByDefault { get { return participateByDefault; } set { participateByDefault = value; Update(); } }
public string Contact { get { return contact; } set { contact = value; Update(); } }
public ListenerState State { get { return state; } }
public delegate void VoidEventHandler();
public event VoidEventHandler Updated;
public event VoidEventHandler CallStatusUpdated;
public event VoidEventHandler CallStarted;
public event VoidEventHandler CallFinished;
public delegate bool ListenerEventHandler(Listener listener);
public event ListenerEventHandler ConnectRequest;
private void Update()
{
SqlConnection connection = SS.Connection();
SqlCommand dbCommand = new SqlCommand("UPDATE listeners SET listenerName = '" + name + "', listenerEnabled = '" + participateByDefault.ToString() + "', listenerContact = '" + contact + "' WHERE listenerId = " + Id, connection);
dbCommand.ExecuteNonQuery();
if (Updated != null) Updated();
connection.Close();
connection.Dispose();
if (Updated != null) Updated();
}
public void Delete()
{
SqlConnection connection = SS.Connection();
SqlCommand dbCommand = new SqlCommand("DELETE FROM listeners WHERE listenerId = " + Id, connection);
dbCommand.ExecuteNonQuery();
connection.Close();
}
public void Toggle()
{
if (state == ListenerState.InCall || state == ListenerState.Calling)
{
Disconnect();
}
else if (state == ListenerState.Disconnected)
{
if (ConnectRequest(this))
state = ListenerState.Ready;
}
else if (state == ListenerState.Ready)
{
state = ListenerState.Disconnected;
}
CallStatusUpdated();
}
public void Connect()
{
if (ConnectRequest != null) ConnectRequest(this);
}
public void Disconnect()
{
if (state == ListenerState.InCall || state == ListenerState.Calling)
{
try
{
Logs.Information("Skype", "Disconnecting listener - Name: " + name + " Handle: " + contact + " Call Id: " + callHandle.Id + " Conference Id: " + callHandle.ConferenceId);
callHandle.Finish();
}
catch (Exception)
{
}
}
}
public void UpdateCallStatus(Call newCallHandle, TCallStatus newCallStatus)
{
callHandle = newCallHandle;
if (state != ListenerState.Disconnected && Sharing.HasCallFinished(newCallStatus))
{
finishedCallDuration = new TimeSpan(0, 0, newCallHandle.Duration);
state = ListenerState.Disconnected;
if (CallFinished != null) CallFinished();
}
else if (state != ListenerState.InCall && Sharing.IsCallInProgress(newCallStatus))
{
state = ListenerState.InCall;
if (CallStarted != null) CallStarted();
}
else if (state != ListenerState.Disconnected && Sharing.HasCallFailed(newCallStatus))
{
finishedCallDuration = new TimeSpan(0, 0, 0);
state = ListenerState.Disconnected;
if (CallFinished != null) CallFinished();
}
else if (Sharing.IsCallRinging(newCallStatus))
{
state = ListenerState.Calling;
}
else if (Sharing.IsAnswerMachine(newCallStatus))
{
Disconnect();
if (CallFinished != null) CallFinished();
}
callStatus = newCallStatus;
CallStatusUpdated();
}
public Listener(int _id)
{
Id = _id;
SqlCommand dbCommand;
SqlDataReader dbReader;
SqlConnection connection = SS.Connection();
dbCommand = new SqlCommand("SELECT * FROM listeners WHERE listenerId = " + Id, connection);
dbReader = dbCommand.ExecuteReader();
dbReader.Read();
name = dbReader["listenerName"].ToString();
contact = dbReader["listenerContact"].ToString();
participateByDefault = (bool)dbReader["listenerEnabled"];
if (participateByDefault) state = ListenerState.Ready;
dbReader.Close();
connection.Close();
}
public Listener(string _name, string _contact, bool _participateByDefault, Congregation _congregation)
{
congregation = _congregation;
SqlConnection connection = SS.Connection();
SqlCommand dbCommand = new SqlCommand("INSERT INTO listeners (listenerName, listenerContact, listenerEnabled, listenerType, listenerCong) VALUES ('" + _name + "', '" + _contact + "', '" + _participateByDefault.ToString() + "', 0, " + congregation.Id + ") SELECT CAST(scope_identity() AS int)", connection);
Id = (int)dbCommand.ExecuteScalar();
connection.Close();
connection.Dispose();
name = _name;
contact = _contact;
participateByDefault = _participateByDefault;
if (participateByDefault) state = ListenerState.Ready;
}
public static ArrayList GetAllListeners(Congregation _cong)
{
SqlCommand dbCommand;
SqlDataReader dbReader;
SqlConnection connection = SS.Connection();
dbCommand = new SqlCommand("SELECT listenerId FROM listeners WHERE listenerCong = " + _cong.Id, connection);
dbReader = dbCommand.ExecuteReader();
ArrayList listeners = new ArrayList();
if (dbReader.HasRows)
{
while (dbReader.Read())
{
listeners.Add(new Listener(int.Parse(dbReader[0].ToString())));
}
}
dbReader.Close();
connection.Close();
return listeners;
}
}
public enum ListenerType
{
Telephone,
Skype
}
public enum ListenerState
{
Ready,
InCall,
Disconnected,
Calling
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace net.callOut
{
class Evaluation
{
public string taskID="0000";
public string name="您";
public string phoneNumber = "910000";
public string dateTime="2015-01-01 01:01:01";
public string department="城管";
public string accidentAddress="大街";
public string evaluationResult="-1";
public string state="1";//0,未创建,-1已删除,-2可以删除
public string lastUpdateTime = "1901-01-01 01:01:01";
public string context="噪音扰民";
public string toIVRTime(string time) {
// tools.log.Debug(dateTime);
string yy, mm, dd,hh,mi,ss;
DateTime dt = Convert.ToDateTime(time);
yy= dt.Year.ToString();//2005
hh=dt.Hour.ToString();//13
dd=dt.Day.ToString();
mi= dt.Minute.ToString();//30
mm= dt.Month.ToString();//11
ss=dt.Second.ToString();//28
return yy+"年"+mm+"月"+dd+"日" +hh+"时"+mi+"分"+ss+"秒";
}
public string toIVRHour(string time)
{
// tools.log.Debug(dateTime);
string yy, mm, dd, hh, mi, ss;
DateTime dt = Convert.ToDateTime(time);
yy = dt.Year.ToString();//2005
hh = dt.Hour.ToString();//13
dd = dt.Day.ToString();
mi = dt.Minute.ToString();//30
mm = dt.Month.ToString();//11
ss = dt.Second.ToString();//28
return yy + "年" + mm + "月" + dd + "日" + hh;
}
public string toIVRDay(string time)
{
// tools.log.Debug(dateTime);
string dd;
DateTime dt = Convert.ToDateTime(time);
dd = dt.Day.ToString();
return dd;
}
public string toTTSDay(string time)
{
// tools.log.Debug(dateTime);
string dd;
DateTime dt = Convert.ToDateTime(time);
dd = dt.Day.ToString();
return dd;
}
public string toIVRMM(string time)
{
string mm;
DateTime dt = Convert.ToDateTime(time);
mm = dt.Month.ToString();//11
return mm;
}
public string toTTSMM(string time)
{
string mm;
DateTime dt = Convert.ToDateTime(time);
mm = dt.Month.ToString();//11
return mm;
}
public string toString(){
return "id : "+taskID + "名字:" + name + "时间 ; "+dateTime + "部门: "+department +
"发生地点:"+accidentAddress + "评论结果:"+evaluationResult + "当前状态:" + state + "最后更新时间:"+lastUpdateTime;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows;
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;
using WpfApplication1.Data;
using System.Windows.Controls;
using System.ComponentModel;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static CommonData cdata;
public GameManager gm = new GameManager();
public Start starter;
public Auction Au;
public Build builder;
public Moneyback vykyp;
public Mortgage zalog;
public MainWindow()
{
InitializeComponent();
cdata = new CommonData(this);
Au = new Auction();
Au.Closing += (s, e) =>
{
e.Cancel = true;
((Window)s).Hide();
};
vykyp = new Moneyback();
vykyp.Closing += (s, e) =>
{
e.Cancel = true;
((Window)s).Hide();
};
zalog = new Mortgage();
zalog.Closing += (s, e) =>
{
e.Cancel = true;
((Window)s).Hide();
};
builder = new Build();
builder.Closing += (s, e) =>
{
e.Cancel = true;
((Window)s).Hide();
};
starter = new Start();
starter.Closing += (s, e) =>
{
e.Cancel = true;
((Window)s).Hide();
};
starter.ShowDialog();
if (cdata.players == null) Close();
//cdata.cPlayer = cdata.players[gm.currentplayerid];
var ttt = (Rectangle)Board.FindName("cPlayer");
var nnn = (Ellipse)Board.FindName("pl" + Convert.ToString(gm.currentplayerid)+"1");
ttt.Fill = nnn.Fill;
gm.gamemngr();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Move.IsEnabled = false;
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (s, ev) =>
{
Thread.Sleep(50);
};
backgroundWorker.RunWorkerCompleted += (s, ev) =>
{
Anigif_dices.Visibility = Visibility.Hidden;
perform_movement();
};
var r = (Image)Board.FindName("r1");
r.Visibility = Visibility.Hidden;
r = (Image)Board.FindName("r2");
r.Visibility = Visibility.Hidden;
Anigif_dices.Visibility = Visibility.Visible;
backgroundWorker.RunWorkerAsync();
}
private void Anigif_dices_MouseDown(object sender, MouseButtonEventArgs e)
{
Anigif_dices.Visibility = Visibility.Hidden;
perform_movement();
}
private void perform_movement()
{
var r1 = gm.d1.Next(1, 6);
var r2 = gm.d2.Next(1, 6);
var dices = r1 + r2;
var dface = (Image)Board.FindName("r1");
dface.Source = new BitmapImage(new Uri("pack://application:,,,/WpfApplication1;component/Resources/" + Convert.ToString(r1) + ".gif"));
dface.Visibility = Visibility.Visible;
dface = (Image)Board.FindName("r2");
dface.Source = new BitmapImage(new Uri("pack://application:,,,/WpfApplication1;component/Resources/" + Convert.ToString(r2) + ".gif"));
dface.Visibility = Visibility.Visible;
cdata.cPlayer.Move(dices);
Move.IsEnabled = true;
//analyse where we are
cdata.cPlayer.PayOrBuy(dices);
if ((r1 != r2) || (!cdata.cPlayer.isalive))
{
//next active player will be currentplayer
gm.currentplayerid++;
if (gm.currentplayerid > cdata.players.Length - 1) gm.currentplayerid = 0;
var active = cdata.players[gm.currentplayerid].isalive;
while (!active)
{
gm.currentplayerid++;
if (gm.currentplayerid > cdata.players.Length - 1) gm.currentplayerid = 0;
active = cdata.players[gm.currentplayerid].isalive;
}
cdata.cPlayer = cdata.players[gm.currentplayerid];
Build.IsEnabled = (cdata.cPlayer.mono.Count != 0);
Mortgage.IsEnabled = Contract.IsEnabled = (cdata.cPlayer.property.Count > 0);
var ttt = (Rectangle)Board.FindName("cPlayer");
var nnn = (Ellipse)Board.FindName("pl" + Convert.ToString(gm.currentplayerid) + "1");
ttt.Fill = nnn.Fill;
PInfo.Text = cdata.cPlayer.name + Convert.ToChar(13) + Convert.ToString(cdata.cPlayer.budget);
var prt = (Image)Board.FindName("portrait");
prt.Source = cdata.cPlayer.face.Source;
}
else
{
Build.IsEnabled = cdata.cPlayer.mono.Count>0;
}
if(!gm.checkplayers())
{
MessageBox.Show(cdata.cPlayer.name +" won!");
starter = new Start();
cdata.cPlayer.drop();
starter.ShowDialog();
}
}
private void Build_Click(object sender, RoutedEventArgs e)
{
builder.bProperty.SelectedItem = null;
builder.bProperty.Items.Clear();
builder.cPlayer.Fill = new SolidColorBrush(MainWindow.cdata.cPlayer.c);
builder.Portrait.Source = cdata.cPlayer.face.Source;
foreach (string m in cdata.cPlayer.mono)
{
var cellList = MainWindow.cdata.cells.Where(x => x.card.color == m).ToList<Cell>();
foreach (Cell cCell in cellList)
{
var i = (Image)FindName(cCell.prop.name + "2");
var ic = (Rectangle)FindName(cCell.prop.name + "1");
var ih = (Image)FindName(cCell.prop.name + "3");
builder.bProperty.Items.Add(new Prop { index = cdata.cells.ToList<Cell>().IndexOf(cCell), name = cCell.prop.name, flag = i, street = ic, bld = ih });
}
}
builder.ShowDialog();
}
private void Prepare_to_quit(object sender, CancelEventArgs e)
{
builder.Closing -= (s, er)=>
{
e.Cancel = true;
((Window)s).Hide();
};
builder.Close();
Au.Closing -= (s, er)=>
{
e.Cancel = true;
((Window)s).Hide();
};
Au.Close();
starter.Closing -= (s,er)=>
{
e.Cancel = true;
((Window)s).Hide();
};
starter.Close();
System.Windows.Application.Current.Shutdown();
}
private void Mortgage_Click(object sender, RoutedEventArgs e)
{
zalog.ShowDialog();
}
}
}
|
using System;
using System.Collections.Generic;
namespace Eratosthenes
{
class Program
{
private static List<long> primeNumbers = new List<long>();
static void Main()
{
primeNumbers.Add(2);
Console.Write(2);
for (long checkValue = 3; checkValue <= 10000000; checkValue += 2)
{
if (IsPrime(checkValue))
{
primeNumbers.Add(checkValue);
Console.Write("\t{0}", checkValue);
}
}
}
private static bool IsPrime(long checkValue)
{
bool isPrime = true;
foreach (int prime in primeNumbers)
{
if ((checkValue % prime) == 0 && prime <= Math.Sqrt(checkValue))
{
isPrime = false;
break;
}
}
return isPrime;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using KartLib.Entities;
using KartObjects;
using KartObjects.Entities;
using KartSystem.Common;
using OnlineOrdersMS;
using KartLib;
using AxisEq;
namespace KartSystem
{
/// <summary>
/// Главный презентор
/// </summary>
public class MainPresenter:BasePresenter
{
#region Конструкторы
/// <summary>
/// Конструктор презентера
/// </summary>
public MainPresenter(IMainView view)
: base()
{
_view = view;
licenseManager = new LicenseManager();
}
#endregion
#region Поля
/// <summary>
/// Интерфейс формы, через которых презентер будет с ней общаться
/// </summary>
private IMainView _view;
public LicenseManager licenseManager;
#endregion
#region Свойства
public string OptionsPath
{
get
{
return Path.Combine(KartLib.Settings.GetExecPath(), "Settings");
}
}
#endregion
#region Методы
public static int CompareCountries(Country x,Country y)
{
return x.Id < y.Id ? -1 : x.Id == y.Id ? 0 : 1;
}
/// <summary>
/// Подгружает необходимые данные для вьюхи
/// </summary>
public override void ViewLoad()
{
Loader.DataContext = DataContext;
Saver.DataContext = DataContext;
//Инициализируем систему событий
if (_view != null)
Loader.DataContext.RemoteEvent += new RemoteEventHandler(_view.DataContext_RemoteEvent);
try //Проверка подключения к базе
{
Loader.DataContext.BeginTransaction();
}
catch //Не удалось подключится
{
string error = "Не удалось подключится к базе данных";// +KartLib.Settings.server + " " + KartLib.Settings.dBase;
Logger.WriteToLog(error);
throw new DbConnectionException(error);
}
//Инициализируем справочные данные
try
{
KartDataDictionary.sDocTypes = Loader.DbLoad<DocType>("1=1 order by name") ?? new List<DocType>();
KartDataDictionary.sWarehouses = Loader.DbLoad<Warehouse>("1=1 order by name") ?? new List<Warehouse>();
KartDataDictionary.sSuppliers = Loader.DbLoad<Supplier>("1=1 order by name") ?? new List<Supplier>();
KartDataDictionary.sAttributeTypes = (Loader.DbLoad<AttributeType>("") ?? new List<AttributeType>());
KartDataDictionary.sParams = new List<AxiTradeParam>();
List<AxiTradeParam> dbParams=Loader.DbLoad<AxiTradeParam>("") ?? new List<AxiTradeParam>();
foreach (var item in EnumExt.ToList(typeof(AxiParamNames)))
{
string value = "";
var v = dbParams.Where(q => q.Name == ((AxiParamNames)item.Id).ToString()).FirstOrDefault();
if (v != null)
value = v.ParamValue;
KartDataDictionary.sParams.Add(new AxiTradeParam() { Id = item.Id, Name = ((AxiParamNames)item.Id).ToString(), ParamDescription = item.Name, ParamType = getParamType(item), ParamGroup = getParamGroup(item), ParamValue=value });
}
foreach (var item in EnumExt.ToList(typeof(AxiExtCardParam)))
{
var v = dbParams.Where(q => q.Name == ((AxiExtCardParam)item.Id).ToString()).FirstOrDefault();
if (v!=null)
KartDataDictionary.sParams.Add(new AxiTradeParam() { Id = item.Id, Name = ((AxiExtCardParam)item.Id).ToString(), ParamDescription = item.Name, ParamType = v.ParamType, ParamGroup = ParamValueGroup.GoodExtParams});
}
//KartDataDictionary.sParams.Add(new AxiTradeParam(){ })
// Loader.DbLoad<AxiTradeParam>("") ?? new List<AxiTradeParam>();
((KartDataDictionary.sCountries = Loader.DbLoad<Country>("") ?? new List<Country>()) as List<Country>).Sort(CompareCountries);
KartDataDictionary.sGoodKinds = Loader.DbLoad<GoodKind>("") ?? new List<GoodKind>();
KartDataDictionary.sPointOfSales = Loader.DbLoad<PointOfSale>("") ?? new List<PointOfSale>();
KartDataDictionary.sPOSGroups = Loader.DbLoad<POSGroup>("") ?? new List<POSGroup>();
KartDataDictionary.sStores = Loader.DbLoad<Store>("") ?? new List<Store>();
KartDataDictionary.sTradeScales = Loader.DbLoad<TradeScale>("") ?? new List<TradeScale>();
KartDataDictionary.sSellers = Loader.DbLoad<Seller>("") ?? new List<Seller>();
KartDataDictionary.sPayTypes = Loader.DbLoad<PayType>("") ?? new List<PayType>();
KartDataDictionary.sCashierRoles = Loader.DbLoad<CashierRole>("") ?? new List<CashierRole>();
KartDataDictionary.sOrganizations = Loader.DbLoad<Organization>("") ?? new List<Organization>();
KartDataDictionary.sMeasures = Loader.DbLoad<Measure>("") ?? new List<Measure>();
KartDataDictionary.sGoodGroups = Loader.DbLoad<GoodGroup>(" 1=1 order by name") ?? new List<GoodGroup>();
KartDataDictionary.sBanks = Loader.DbLoad<Bank>("") ?? new List<Bank>();
KartDataDictionary.sPriceListHeads = Loader.DbLoad<PriceListHead>("") ?? new List<PriceListHead>();
KartDataDictionary.sUsers = Loader.DbLoad<User>("");
KartDataDictionary.sWhSections = Loader.DbLoad<WhSection>("") ?? new List<WhSection>();
KartDataDictionary.sProducer = Loader.DbLoad<Producer>("") ?? new List<Producer>();
KartDataDictionary.sCashAccount = Loader.DbLoad<CashAccount>("") ?? new List<CashAccount>();
KartDataDictionary.sCustomer = Loader.DbLoad<Customer>("") ?? new List<Customer>();
KartDataDictionary.sCashOperation = Loader.DbLoad<KartObjects.CashOperation>("") ?? new List<KartObjects.CashOperation>();
KartDataDictionary.sPromoAction = Loader.DbLoad<PromoAction>("") ?? new List<PromoAction>();
KartDataDictionary.sDocStatuses = KartDataDictionary.InitDocStatuses();
KartDataDictionary.sDeliveryMethods = EnumExt.ToList(typeof(DeliveryMethod));
KartDataDictionary.sPaymentMethods = EnumExt.ToList(typeof(PaymentMethod));
KartDataDictionary.sOrderStatuses = EnumExt.ToList(typeof(OrderStatus));
KartDataDictionary.sOrderLineStatuses = EnumExt.ToList(typeof(OrderLineStatus));
KartDataDictionary.sOrderPaymentStatuses = EnumExt.ToList(typeof(PaymentStatus));
KartDataDictionary.sOrderUploadStatuses = EnumExt.ToList(typeof(UploadStatus));
KartDataDictionary.sPriceTypes = EnumExt.ToList(typeof(PriceListType));
KartDataDictionary.sCashTypes = EnumExt.ToList(typeof(CashType));
KartDataDictionary.sNDSRate = Loader.DbLoad<NDSRate>("");
KartDataDictionary.sAlcoTypes = Loader.DbLoad<AlcoType>("");
Loader.DataContext.CommitTransaction();
KartDataDictionary.sDocKinds = new List<DocKindRecord>();
KartDataDictionary.sDocKinds.Add(new DocKindRecord { Id = 1, Name="Документы" });
var vdk = (from s in KartDataDictionary.sDocTypes select s.DocKind).Distinct().OrderBy(q=>(int)q);
int i = 2;
foreach (DocKindEnum item in vdk)
{
KartDataDictionary.sDocKinds.Add(new DocKindRecord { Id = i, IdParent = 1, docKind = item, Name = item.GetDescription() });
i++;
}
foreach (DocType dt in KartDataDictionary.sDocTypes)
{
DocKindRecord parent= (from d in KartDataDictionary.sDocKinds where d.docKind==dt.DocKind && d.IdParent==1 select d).FirstOrDefault();
if (parent!=null)
KartDataDictionary.sDocKinds.Add(new DocKindRecord { Id = i, IdParent = parent.Id, docKind = parent.docKind , Name = dt.Name, IdDocType=dt.Id });
i++;
}
}
catch (Exception e1)
{
Logger.WriteToLog("Ошибка инициализации справочных данных " + e1.Message);
throw;
}
}
private ParamValueGroup getParamGroup(SimpleNamedEntity item)
{
return ParamValueGroup.AxitradeParams;
}
private ParamValueType getParamType(SimpleNamedEntity item)
{
switch (((AxiParamNames)item.Id).ToString())
{
case "InternalBarcodePrefix":
{
return ParamValueType.String;
}
case "UseExternalSuppliers":
{
return ParamValueType.Boolean;
}
case "DefaultIdSupplier":
{
return ParamValueType.Decimal;
}
case "DefaultIdCountry":
{
return ParamValueType.Decimal;
}
case "VolumeMeasure":
{
return ParamValueType.String;
}
case "UseAssortment":
{
return ParamValueType.Boolean;
}
case "UseReturnPriceControl":
{
return ParamValueType.Boolean;
}
case "WeightBarcodePrefix":
{
return ParamValueType.String;
}
case "SaleDocByShift":
{
return ParamValueType.Boolean;
}
case "SystemBarcodePrefix":
{
return ParamValueType.String;
}
case "IsEditArticul":
{
return ParamValueType.Boolean;
}
case "RoundPrice":
{
return ParamValueType.Decimal;
}
case "AutoSelectSpec":
{
return ParamValueType.Boolean;
}
case "AutoAcceptRevDoc":
{
return ParamValueType.Boolean;
}
case "UseActiveDocSupplier":
{
return ParamValueType.Boolean;
}
case "SearchActsQuantity":
{
return ParamValueType.Boolean;
}
case "UpdateGoodSupplier":
{
return ParamValueType.Boolean;
}
case "MergeSpecPriceMode":
{
return ParamValueType.Boolean;
}
case "DenyRetPrice":
{
return ParamValueType.Boolean;
}
case "AutoSelectDocumentSupplier":
{
return ParamValueType.Boolean;
}
case "UseAxiCloud":
{
return ParamValueType.Boolean;
}
case "ManualBCDetection":
{
return ParamValueType.Boolean;
}
case "CheckEAN13":
{
return ParamValueType.Boolean;
}
default:
return ParamValueType.String;
}
}
/// <summary>
/// Событие, возникающее перед наступлением очередного этапа загрузки формы
/// </summary>
public event EventHandler LoadingStatusChanged;
private void RaiseLoadingStatusChanged(string newStatus)
{
if (LoadingStatusChanged != null)
{
LoadingStatusChanged(newStatus, EventArgs.Empty);
}
}
public void LoadSettings()
{
RaiseLoadingStatusChanged("Загрузка параметров...");
// Загружаем параметры из файла настроек
if (!KartLib.Settings.LoadSettings("config.xml"))
{
const string error = "Не удалось загрузить настройки из файла конфигурации.";
Logger.WriteToLog(error);
throw new ConfigLoadException(error);
}
}
#endregion
}
}
|
using System;
using System.Data;
namespace DMS.Presentation
{
/// <summary>
///
/// </summary>
public interface IDataViewer
{
DataTable DataSource{get;}
void InitData();
void BindDataToControl();
void RefreshDB();
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TinhLuong.Models;
using TinhLuongBLL;
namespace TinhLuong.Controllers
{
public class ImportDonDichMangCapDongController : BaseController
{
// GET: ImportDonDichMangCapDong
SaveLog sv = new SaveLog();
[CheckCredential(RoleID = "IMPORT_EXCELPTTB_KDTM")]
public ActionResult Index()
{
// sv.save(Session[SessionCommon.Username].ToString(), "Cap Nhat tu file->Cac Khoan thu Nhap Ky 1");
return View();
}
/// <summary>
/// View data befor import
/// </summary>
/// <returns></returns>
[CheckCredential(RoleID = "IMPORT_EXCELPTTB_KDTM")]
public ActionResult Success()
{
try
{
DataTable dt = (DataTable)Session["dtImport"];
dt.Columns.Add("DonGia", typeof(String));
dt.Columns.Add("ThanhTien", typeof(String));
if (dt.Rows.Count > 0 || dt != null)
{
string cl0 = dt.Rows[0]["LoaiCap"].ToString();
string cl1 = dt.Rows[0]["NhanSuID"].ToString();
string cl2 = dt.Rows[0]["SoKM"].ToString();
string cl3 = dt.Rows[0]["Nam"].ToString();
string cl4 = dt.Rows[0]["Thang"].ToString();
for(int i=0; i<dt.Rows.Count; i++)
{
DataTable DonGia = new CommonBLL().GetDonGia("DONDICH",dt.Rows[i]["LoaiCap"].ToString());
dt.Rows[i]["DonGia"] = DonGia.Rows[0]["DonGia"].ToString();
dt.Rows[i]["ThanhTien"] = int.Parse(DonGia.Rows[0]["DonGia"].ToString())*int.Parse(dt.Rows[i]["SoKM"].ToString());
}
return View(dt);
}
else if (dt.Rows.Count == 0 || dt == null)
{
setAlert("Cấu trúc tệp không chính xác hoặc không có dữ liệu để import", "error");
return Redirect("/import-dondichcap");
}
else
{
setAlert("Cấu trúc tệp không chính xác. Vui lòng chọn lại tệp!", "error");
return Redirect("/import-dondichcap");
}
}
catch
{
setAlert("Cấu trúc tệp không chính xác. Vui lòng chọn lại tệp!", "error");
return Redirect("/import-dondichcap");
}
}
/// <summary>
/// import data to db
/// </summary>
/// <returns></returns>
[CheckCredential(RoleID = "IMPORT_EXCELPTTB_KDTM")]
public ActionResult ImportDB()
{
DataTable dt = (DataTable)Session["dtImport"];
string rows = "",reason="";
int dem = 0;
if (dt.Rows.Count > 0)
{
if (new ImportExcelBLL().GetChotSo(int.Parse(dt.Rows[0]["Thang"].ToString()), int.Parse(dt.Rows[0]["Nam"].ToString()), Session[SessionCommon.DonViID].ToString(), "BangLuong") == false)
{
sv.save(Session[SessionCommon.Username].ToString(), "Cập nhật từ file->Import dồn dịch mạng cáp đồng->Import not success- Thang-" + dt.Rows[0]["Thang"].ToString() + "-nam-" + dt.Rows[0]["Nam"].ToString() + "-Do tháng lương đã chốt");
setAlert("Dữ liệu đã chốt, không tiếp tục cập nhật được!", "error");
}
else
{
bool checkDelete= new ImportExcelBLL().Delete_LuongKhac(int.Parse(dt.Rows[0]["Nam"].ToString()), int.Parse(dt.Rows[0]["Thang"].ToString()), Session[SessionCommon.Username].ToString(),6, Session[SessionCommon.DonViID].ToString());
if (checkDelete)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
try
{
string checkNhanSuID = new PhanQuyenBLL().CheckNhanVien_InDonVi(int.Parse(dt.Rows[0]["Thang"].ToString()), int.Parse(dt.Rows[0]["Nam"].ToString()), Session[SessionCommon.DonViID].ToString(), dt.Rows[0]["NhanSuID"].ToString());
if (checkNhanSuID == "EXISTS")
{
DataTable DonGia = new CommonBLL().GetDonGia("DONDICH",dt.Rows[i]["LoaiCap"].ToString());
var rs = new ImportExcelBLL().Update_LUONGKHAC(int.Parse(dt.Rows[i]["Nam"].ToString()), int.Parse(dt.Rows[i]["Thang"].ToString()), Session[SessionCommon.Username].ToString(), int.Parse(DonGia.Rows[0]["DonGia"].ToString()) * int.Parse(dt.Rows[0]["SoKM"].ToString()), dt.Rows[i]["NhanSuID"].ToString(), "DDCD");
if (rs) dem++;
else
{
reason = "không thể cập nhật dữ liệu";
rows = rows == "" ? rows + "" + ((i + 1).ToString()) : rows + ", " + ((i + 1).ToString());
}
}
else
{
reason = "nhân viên không tồn tại trong đơn vị";
rows = rows == "" ? rows + "" + ((i + 1).ToString()) : rows + ", " + ((i + 1).ToString());
}
}
catch(Exception e)
{
reason = "ERROR:"+e.Message+"::không thể cập nhật dữ liệu";
rows = rows == "" ? rows + "" + ((i + 1).ToString()) : rows + ", " + ((i + 1).ToString());
continue;
}
}
if (dem == dt.Rows.Count)
{
Session.Remove("dtImport");
sv.save(Session[SessionCommon.Username].ToString(), "Cap Nhat tu file->Import phiếu báo hỏng giảm trừ->Import Thanh Cong");
setAlert("Import dữ liệu thành công", "success");
return Redirect("/import-dondichcap");
}
else if (0 < dem && dem < dt.Rows.Count)
{
string msg1 = " Dòng " + rows.ToString() + " import không thành công. Lỗi::"+reason;
setAlertTime(msg1, "error");
sv.save(Session[SessionCommon.Username].ToString(), "Cap Nhat tu file->Import phiếu báo hỏng giảm trừ->Import khong Thanh Cong- Thang-" + dt.Rows[0]["Thang"].ToString() + "-nam-" + dt.Rows[0]["Nam"].ToString() + "-Dong import k thanh cong-" + rows+ " Lỗi::"+reason);
return Redirect("/import-dondichcap");
}
else
{
sv.save(Session[SessionCommon.Username].ToString(), "Cap Nhat tu file->Import phiếu báo hỏng giảm trừ->Import khong Thanh Cong");
setAlert("Import dữ liệu không thành công import không thành công. Vui lòng import lại", "error");
}
}
else
{
setAlert("Import dữ liệu không thành công import không thành công. Vui lòng import lại", "error");
}
}
}
else
{
setAlert("Không có dữ liệu để import!", "error");
}
return Redirect("/import-dondichcap");
}
/// <summary>
/// read file import to get data
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[HttpPost]
public ActionResult ImportexcelToDb(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
string fileName = "fileUpload_" + Session[SessionCommon.Username].ToString() + "_" + DateTime.Now.Year + "" + DateTime.Now.Month + "" + DateTime.Now.Day + "" + DateTime.Now.Hour + "" + DateTime.Now.Minute + "" + DateTime.Now.Second + "_" + file.FileName;
string path1 = Path.Combine(Server.MapPath("~/Assets/Uploads/Import/"), RemoveUnicode.ConvertToUnsign2(fileName));
string extension = Path.GetExtension(file.FileName);
string connString = "";
file.SaveAs(path1 + "" + extension);
path1 = path1 + "" + extension;
string[] validFileTypes = { ".xls", ".xlsx", ".csv" };
DataTable dt;
if (validFileTypes.Contains(extension))
{
if (extension == ".csv")
{
dt = Utility.ConvertCSVtoDataTable(path1);
Session["dtImport"] = dt;
}
//Connection String to Excel Workbook
else if (extension == ".xls")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 8.0;";
//connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path1 + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
try
{
dt = Utility.ConvertXSLXtoDataTable(path1, connString);
Session["dtImport"] = dt;
}
catch (Exception ex)
{
setAlert(ex.ToString(), "success");
}
}
else if (extension == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
dt = Utility.ConvertXSLXtoDataTable(path1, connString);
Session["dtImport"] = dt;
}
DataTable dt1 = (DataTable)Session["dtImport"];
System.IO.File.Delete(path1);
return Redirect("/import-dondichcap/doc-file");
}
else
{
setAlert("Vui lòng chỉ Upload tệp có định dạng .xls, .xlsx hoặc .csv", "error");
}
}
else
{
setAlert("Vui lòng chọn file", "error");
}
return Redirect("/import-dondichcap");
}
}
}
|
using PersonasPhone.Entidades;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PersonasPhone.UI.Registros
{
public partial class TypeTelefonoForm : Form
{
public TypeTelefonoForm()
{
InitializeComponent();
}
private void Limpiar()
{
IdnumericUpDown.Value = 0;
TelefonotextBox.Clear();
}
private bool Validar(int error)
{
bool paso = false;
if (error == 1 && IdnumericUpDown.Value == 0)
{
errorProvider.SetError(IdnumericUpDown,
"Debe introducir un Id");
paso = true;
}
if (error == 2 && TelefonotextBox.Text == string.Empty)
{
errorProvider.SetError(TelefonotextBox,
"Debe ingresar una Descripcion");
paso = true;
}
return paso;
}
private void LlenarCampos()
{
TelefonoDetalle telefonoDetalle = new TelefonoDetalle();
TelefonotextBox.Text = telefonoDetalle.Telefonos.ToString();
}
private TelefonoDetalle LlenaClase()
{
TelefonoDetalle tipoPartido = new TelefonoDetalle();
if (IdnumericUpDown.Value == 0)
{
tipoPartido.id = 0;
}
else
{
tipoPartido.TipoPartidoId = Convert.ToInt32(IdnumericUpDown.Value);
}
tipoPartido.Descripcion = DescripciontextBox.Text;
return tipoPartido;
}
private void Buscarbutton_Click(object sender, EventArgs e)
{
if (Validar(1))
{
MessageBox.Show("Favor de llenar la casilla para poder Buscar");
}
else
{
int id = Convert.ToInt32(IdnumericUpDown.Value);
tipoPartido = BLL.TipoPartidosBLL.Buscar(id);
if (tipoPartido != null)
{
IdnumericUpDown.Value = tipoPartido.TipoPartidoId;
DescripciontextBox.Text = tipoPartido.Descripcion.ToString();
}
else
{
MessageBox.Show("No Fue Encontrado!", "Fallido", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
errorProvider.Clear();
}
}
private void Nuevobutton_Click(object sender, EventArgs e)
{
}
private void Guardarbutton_Click(object sender, EventArgs e)
{
if (Validar(2))
{
MessageBox.Show("Llenar Campos vacios");
errorProvider.Clear();
return;
}
else
{
tipoPartido = LlenaClase();
if (IdnumericUpDown.Value == 0)
{
if (BLL.TipoPartidosBLL.Guardar(tipoPartido))
{
MessageBox.Show("Guardado!", "Exitoso", MessageBoxButtons.OK, MessageBoxIcon.Information);
Limpiar();
}
else
{
MessageBox.Show("No se pudo Guardar!!");
}
}
else
{
var result = MessageBox.Show("Seguro de Modificar?", "+TipoPartidos",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
if (BLL.TipoPartidosBLL.Modificar(LlenaClase()))
{
MessageBox.Show("Modificado!!");
Limpiar();
}
else
{
MessageBox.Show("No se pudo Guardar!!");
}
}
}
Limpiar();
errorProvider.Clear();
}
}
private void Eliminarbutton_Click(object sender, EventArgs e)
{
if (Validar(1))
{
MessageBox.Show("Favor de llenar casilla para poder Eliminar");
}
var result = MessageBox.Show("Seguro de Eliminar?", "+Tipo de Partidos",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
if (BLL.PartidosBLL.Eliminar(Convert.ToInt32(IdnumericUpDown.Value)))
{
MessageBox.Show("Eliminado");
Limpiar();
}
else
{
MessageBox.Show("No se pudo eliminar");
}
}
}
}
}
}
|
using HouseRent.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace HouseRent.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<PropertyType> PropertyTypes { get; set; }
public DbSet<Flat> Flats { get; set; }
public DbSet<DetailOfFlat> DetailOfFlats { get; set; }
public DbSet<DetailOfDuplex> DetailOfDuplexs { get; set; }
public DbSet<Booking> Bookings { get; set; }
public DbSet<BookingDetail> BookingDetails { get; set; }
public DbSet<BookingDetail2> bookingDetail2s { get; set; }
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
}
}
|
using ApiSGCOlimpiada.Models;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSGCOlimpiada.Data.SolicitacaoCompraDAO
{
public class SolicitacaoCompraDAO : ISolicitacaoCompraDAO
{
private readonly string _conn;
public SolicitacaoCompraDAO(IConfiguration config)
{
_conn = config.GetConnectionString("conn");
}
MySqlConnection conn;
MySqlCommand cmd;
MySqlDataAdapter adapter;
DataTable dt;
public bool Add(SolicitacaoCompra solicitacaoCompra)
{
try
{
conn = new MySqlConnection(_conn);
cmd = new MySqlCommand($"insert into SolicitacaoCompras values (null,'{solicitacaoCompra.ResponsavelEntrega}', " +
$"'{solicitacaoCompra.Data.ToString("yyyy-MM-dd HH:mm")}', '{solicitacaoCompra.Justificativa}', '{solicitacaoCompra.Anexo}', {solicitacaoCompra.TipoCompraId}, {solicitacaoCompra.EscolaId})", conn);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
public SolicitacaoCompra Find(long id)
{
try
{
conn = new MySqlConnection(_conn);
cmd = new MySqlCommand($"Select * from SolicitacaoCompras where id = {id}", conn);
conn.Open();
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
SolicitacaoCompra solicitacaoCompra = null;
foreach (DataRow item in dt.Rows)
{
solicitacaoCompra = new SolicitacaoCompra();
solicitacaoCompra.Id = Convert.ToInt32(item["id"]);
solicitacaoCompra.ResponsavelEntrega = item["responsavelEntrega"].ToString();
solicitacaoCompra.Data = Convert.ToDateTime(item["Data"]);
solicitacaoCompra.Justificativa = item["Justificativa"].ToString();
solicitacaoCompra.TipoCompraId = Convert.ToInt32(item["tipoComprasId"]);
solicitacaoCompra.EscolaId = Convert.ToInt32(item["EscolasId"]);
solicitacaoCompra.Anexo = item["Anexo"].ToString();
}
return solicitacaoCompra;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
conn.Close();
}
}
public IEnumerable<SolicitacaoCompra> GetAll()
{
try
{
List<SolicitacaoCompra> solicitacaoCompras = new List<SolicitacaoCompra>();
conn = new MySqlConnection(_conn);
cmd = new MySqlCommand($"Select * from solicitacaocompras", conn);
conn.Open();
adapter = new MySqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
SolicitacaoCompra solicitacaoCompra = null;
foreach (DataRow item in dt.Rows)
{
solicitacaoCompra = new SolicitacaoCompra();
solicitacaoCompra.Id = Convert.ToInt64(item["id"]);
solicitacaoCompra.ResponsavelEntrega = item["responsavelEntrega"].ToString();
solicitacaoCompra.Data = Convert.ToDateTime(item["Data"]);
solicitacaoCompra.Justificativa = item["Justificativa"].ToString();
solicitacaoCompra.TipoCompraId = Convert.ToInt64(item["tipoComprasId"]);
solicitacaoCompra.EscolaId = Convert.ToInt64(item["EscolasId"]);
solicitacaoCompra.Anexo = item["Anexo"].ToString();
solicitacaoCompras.Add(solicitacaoCompra);
}
return solicitacaoCompras;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
finally
{
conn.Close();
}
}
public bool Update(SolicitacaoCompra solicitacaoCompra, long id)
{
try
{
conn = new MySqlConnection(_conn);
cmd = new MySqlCommand($"Update SolicitacaoCompras set responsavelEntrega = '{solicitacaoCompra.ResponsavelEntrega}', " +
$"data = '{solicitacaoCompra.Data.ToString("yyyy-MM-dd HH:mm")}', justificativa = '{solicitacaoCompra.Justificativa}', tipoComprasId = {solicitacaoCompra.TipoCompraId}, escolasId = {solicitacaoCompra.EscolaId}, anexo = '{solicitacaoCompra.Anexo}' where id = {id}", conn);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
public bool AnexarNotaFiscal(string fileName, long id)
{
try
{
conn = new MySqlConnection(_conn);
cmd = new MySqlCommand($"Update SolicitacaoCompras set anexo = '{fileName}' where id = {id}", conn);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
return true;
}
return false;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
}
finally
{
conn.Close();
}
}
}
}
|
using FeriaVirtual.Domain.SeedWork.Events;
using System.Collections.Generic;
namespace FeriaVirtual.Domain.Models.Users.Events
{
class UserWasUpdated
: DomainEventBase
{
public UserWasUpdated()
: base() { }
public UserWasUpdated
(DomainEventId eventId, Dictionary<string, object> body)
: base(eventId, body) { }
public override string EventName() =>
"User.Updated";
public override DomainEventBase FromPrimitives
(DomainEventId eventId, Dictionary<string, object> body) =>
new UserWasUpdated(eventId, body);
}
}
|
using Microsoft.Extensions.Logging;
using System;
namespace DelegateLogging
{
public class GenericLoggerProvider : ILoggerProvider
{
private Func<string, ILogger>? _createLogger;
public GenericLoggerProvider(Func<string, ILogger> createLogger)
{
_createLogger = createLogger;
}
public ILogger CreateLogger(string categoryName)
{
var logger = _createLogger?.Invoke(categoryName);
return logger != null ? logger : throw new InvalidOperationException();
}
#pragma warning disable CA1816 // Dispose methods should call SuppressFinalize
public void Dispose() => _createLogger = null;
#pragma warning restore CA1816 // Dispose methods should call SuppressFinalize
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebUI.Entity;
namespace WebUI.Data.Abstract
{
public interface IMessageRepository
{
Message GetById(int messageId);
IQueryable<Message> GetAll();
void AddMessage(Message message);
void DeleteMessage(int messageId);
void SaveMessage(Message message);
}
}
|
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace Tests
{
public class TestEnemySpawner
{
EnemySpawner enemySpawner;
[OneTimeSetUp]
public void TestSetUp()
{
enemySpawner = new GameObject().AddComponent<EnemySpawner>();
}
[Test]
public void TestEnemySpawnForZeroValues()
{
float radius = 1f;
float angle = 0f;
Vector3 enemyPosition = enemySpawner.GetPosition(Vector3.zero, radius, angle);
Vector3 expected = new Vector3(1, 0, 0);
Assert.AreEqual(expected, enemyPosition);
}
[Test]
public void TestEnemySpawnForLargeRadius()
{
float radius = 3f;
float angle = 0f;
Vector3 enemyPosition = enemySpawner.GetPosition(Vector3.zero, radius, angle);
Vector3 expected = new Vector3(3, 0, 0);
Assert.AreEqual(expected, enemyPosition);
}
[Test]
public void TestEnemySpawnForNegativeRadius()
{
float radius = -5f;
float angle = 0f;
Vector3 enemyPosition = enemySpawner.GetPosition(Vector3.zero, radius, angle);
Vector3 expected = new Vector3(5, 0, 0);
Assert.AreEqual(expected, enemyPosition);
}
[Test]
public void TestEnemySpawnForZeroRadius()
{
float radius = 0;
float angle = 0f;
Vector3 enemyPosition = enemySpawner.GetPosition(Vector3.zero, radius, angle);
Vector3 expected = new Vector3(1, 0, 0);
Assert.AreEqual(expected, enemyPosition);
}
[Test]
public void TestEnemySpawnForPlayerPosisionOne()
{
float radius = 4;
float angle = 0f;
Vector3 playerPosition = Vector3.one;
Vector3 enemyPosition = enemySpawner.GetPosition(playerPosition, radius, angle);
Vector3 expected = new Vector3(5, 1, 1);
Assert.AreEqual(expected, enemyPosition);
}
[Test]
public void TestEnemySpawnForRadiusSmallerThanOne()
{
float radius = 0.5f;
float angle = 0f;
Vector3 playerPosition = Vector3.one;
Vector3 enemyPosition = enemySpawner.GetPosition(playerPosition, radius, angle);
Vector3 expected = new Vector3(2, 1, 1);
Assert.AreEqual(expected, enemyPosition);
}
[Test]
public void TestEnemySpawnForPlayerPosisionVariableAndAngleVariable()
{
float radius = 4;
float angle = Mathf.PI / 4;
Vector3 playerPosition = new Vector3(3, 4, 6);
Vector3 enemyPosition = enemySpawner.GetPosition(playerPosition, radius, angle);
Vector3 expected = new Vector3(5.8f, 4, 8.8f);
Assert.AreEqual(expected.x, enemyPosition.x, 0.1f, "Positions differ x", null);
Assert.AreEqual(expected.y, enemyPosition.y, 0.1f, "Positions differ y", null);
Assert.AreEqual(expected.z, enemyPosition.z, 0.1f, "Positions differ z", null);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Patterns.Pattern.Ef6;
namespace Welic.Dominio.Models.Contratos.Map
{
public class ContratosMap : Entity
{
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Vampire : MonoBehaviour
{
public string Name;
public int[] Relations;
public int getRelation(int player)
{
return Relations[player];
}
public void setName(string nam) { Name = nam; }
public string getName()
{
return Name;
}
void Start() {
Relations = new int[] { 0, 0, 0, 0 };
DontDestroyOnLoad(this.gameObject);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bit8Piano.Model.Sequencer.ADSR
{
struct Phase : IPhase
{
double duration;
double start;
double strength;
public double Duration { get { return duration; } set { duration = value; } }
public double Start { get { return start; } set { start = value; } }
public double Strength { get { return strength; } set { strength = value; } }
public Phase(double duration, double start, double end)
{
this.duration = duration;
this.start = start;
this.strength = end;
}
}
public static class AttackPhase
{
public const double strength = 32767.0;
public const double duration = (double)1 / 20;
}
public static class DecayPhase
{
public const double strength = 18000.0;
public const double duration = (double)1 / 9;
}
public static class SustainPhase
{
public const double strength = 14000.0;
public const double duration = (double)1 / 4;
}
public static class ReleasePhase
{
public const double strength = 0.0;
public const double duration = (double)1 / 6;
}
}
|
using EPI.Sorting;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EPI.UnitTests.Sorting
{
[TestClass]
public class InPlaceMergeSortUnitTest
{
[TestMethod]
public void InPlaceMerge()
{
int?[] A = new int?[] { 5, 13, 17, null, null, null, null, null };
int?[] B = new int?[] { 3, 7, 11, 19 };
InPlaceMergeSort.Sort(A, B);
A.ShouldBeEquivalentTo(new int?[] { 3, 5, 7, 11, 13, 17, 19, null });
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using POSServices.Models;
using POSServices.WebAPIModel;
namespace POSServices.Data
{
public class AuthRepository : IAuthRepository
{
private readonly DB_BIENSI_POSContext _context;
public AuthRepository(DB_BIENSI_POSContext context)
{
_context = context;
}
public async Task<UserLogin> Login(string username, string password)
{
var employeecode = await _context.Employee.Where(c => c.EmployeeCode == username).Select(c => c.Id).FirstOrDefaultAsync();
// var login = await _context.UserLogin.FirstOrDefaultAsync(x => x.UserId == Int32.Parse(username));
var login = await _context.UserLogin.FirstOrDefaultAsync(x => x.UserId == employeecode);
if (login == null)
{
return null;
}
if (!VerifyPasswordHash(password, login.PasswordHash, login.PasswordSalt))
{
return null;
}
login.LastLogin = DateTime.UtcNow;
_context.Update(login);
await _context.SaveChangesAsync();
//auth sukses
return login;
}
private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
{
using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
{
var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
for (int i = 0; i < computedHash.Length; i++)
{
if (computedHash[i] != passwordHash[i]) return false;
}
}
return true;
}
public async Task<UserLogin> Register(UserLogin login, string password)
{
byte[] passwordHash, passwordSalt;
CreatePasswordHash(password, out passwordHash, out passwordSalt);
login.PasswordHash = passwordHash;
login.PasswordSalt = passwordSalt;
await _context.UserLogin.AddAsync(login);
await _context.SaveChangesAsync();
return login;
}
private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
{
using (var hmac = new System.Security.Cryptography.HMACSHA512())
{
passwordSalt = hmac.Key;
passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
public async Task<bool> UserExists(string username)
{
if (await _context.UserLogin.AnyAsync(x => x.UserId == Int32.Parse(username)))
return true;
return false;
}
}
}
|
using ISE.SM.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ISE.SM.Common.Message
{
[DataContract]
public class SignInMessage
{
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Password
{
get;
set;
}
public string PlainPassword
{
get
{
try
{
RSAEncryptionCreator encryption = new RSAEncryptionCreator();
return encryption.PrivateDecryption(Password);
}
catch
{
return string.Empty;
}
}
}
[DataMember]
public string ClientId { get; set; }
}
public class SignInMessageBuilder
{
public SignInMessageBuilder()
{
}
public static SignInMessage BuildMessage(string userName, string password, string clientId)
{
SignInMessage msg = new SignInMessage()
{
ClientId=clientId,
UserName=userName
};
RSAEncryptionCreator encryption = new RSAEncryptionCreator();
msg.Password = encryption.PublicEncryption(password);
return msg;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using PterodactylCharts;
using Xunit;
namespace UnitTestEngine
{
public class TestGraphLegendHelper : TheoryData<string, int, string>
{
public TestGraphLegendHelper()
{
Add("Title example", 0, "Graph Legend" + Environment.NewLine + "Title: Title example"+ Environment.NewLine + "Position: 0");
Add("Title example", 12, "Graph Legend" + Environment.NewLine + "Title: Title example"+ Environment.NewLine + "Position: 12");
}
}
public class TestGraphLegendExceptionHelper : TheoryData<string, int, string>
{
public TestGraphLegendExceptionHelper()
{
Add("Title example", -1, "Position should be between 0 and 12");
Add("Title example", 13, "Position should be between 0 and 12");
}
}
public class TestGraphLegend
{
[Theory]
[ClassData(typeof(TestGraphLegendHelper))]
public void CorrectData(string title, int position, string toString)
{
GraphLegend testObject = new GraphLegend(title, position);
Assert.Equal(title, testObject.Title);
Assert.Equal(position, testObject.Position);
Assert.Equal(toString, testObject.ToString());
}
[Theory]
[ClassData(typeof(TestGraphLegendExceptionHelper))]
public void CheckExceptions(string title, int position, string message)
{
var exception = Assert.Throws<ArgumentException>(() => new GraphLegend(title, position));
Assert.Equal(message, exception.Message);
}
}
}
|
using DevExpress.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Runtime.InteropServices;
using WpfGridControlTest01.Classes;
namespace WpfGridControlTest01.Models
{
public class Product3 : BindableBase
{
public Product3()
{
}
bool _IsMine = false;
public bool IsMine {
get { return _IsMine; }
set { SetValue(ref _IsMine, value); }
}
bool _Chk1;
public bool Chk1 {
get { return _Chk1; }
set { SetValue(ref _Chk1, value); }
}
string _BandWide;
public string BandWide {
get { return _BandWide; }
set { SetValue(ref _BandWide, value); }
}
bool _Chk2;
public bool Chk2 {
get { return _Chk2; }
set { SetValue(ref _Chk2, value); }
}
string _Freq;
public string Freq {
get { return _Freq; }
set { SetValue(ref _Freq, value); }
}
public T InputStruct<T>() where T : struct
{
T stuff = new T();
var properties = this.GetType().GetProperties();
foreach (var p in properties)
{
// var name0 = stuff.GetType().GetField("BandWide");
// var name = stuff.GetType().GetField(p.Name).GetValue(stuff).GetType().Name;
var name = stuff.GetType().GetField(p.Name).FieldType.Name;
switch (name)
{
case "Byte":
stuff.GetType().GetField(p.Name).SetValue(stuff, Convert.ToByte(p.GetValue(this)));
break;
case "Char[]":
var size = (stuff.GetType().GetField(p.Name).GetCustomAttributes(true)[0] as MarshalAsAttribute).SizeConst;
string str = p.GetValue(this).ToString();
char[] srcArr = str.ToCharArray();
char[] tmpArr = new char[size];
Array.Copy(srcArr, tmpArr, srcArr.Length);
stuff.GetType().GetField(p.Name).SetValue(stuff, tmpArr);
break;
}
}
return stuff;
}
}
}
|
using System;
using System.Collections.Generic;
namespace ResilienceClasses
{
public class clsLoanRecording
{
#region Enums and Static Values
public static string strLoanRecordingPath = "/Volumes/GoogleDrive/Shared Drives/Resilience/tblLoanRecording.csv";
public static int IndexColumn = 0;
public static int LoanIDColumn = 1;
public static int RecordingDateColumn = 2;
public static int BookColumn = 3;
public static int PageColumn = 4;
public static int InstrumentColumn = 5;
public static int ParcelColumn = 6;
#endregion
#region Properties
private int iRecordingID;
private int iLoanID;
private int iBook;
private int iPage;
private int iInstrument;
private int iParcel;
private DateTime dtRecording;
#endregion
#region Constructors
public clsLoanRecording()
{
this.init();
}
public clsLoanRecording(string propertyAddress)
{
this._LoadByAddress(propertyAddress, new clsCSVTable(clsLoanRecording.strLoanRecordingPath));
}
public clsLoanRecording(string propertyAddress, clsCSVTable tbl)
{
this._LoadByAddress(propertyAddress, tbl);
}
public clsLoanRecording(int loanID, int book, int page, int instrument, int parcel, DateTime dt, int loanRecordingID = -1)
{
if (loanRecordingID < 0) { this.iRecordingID = this._NewLoanRecordingID(new clsCSVTable(clsLoanRecording.strLoanRecordingPath)); }
else { this.iRecordingID = loanRecordingID; }
this.iLoanID = loanID;
this.iBook = book;
this.iPage = page;
this.iInstrument = instrument;
this.iParcel = parcel;
this.dtRecording = dt;
}
#endregion
#region PropertyAccessors
public int ID() { return this.iRecordingID; }
public int LoanID() { return this.iLoanID; }
public int Book() { return this.iBook; }
public int Page() { return this.iPage; }
public int Instrument() { return this.iInstrument; }
public int Parcel() { return this.iParcel; }
public DateTime RecordingDate() { return this.dtRecording; }
#endregion
#region DB Methods
public bool Save(string path)
{
clsCSVTable tbl = new clsCSVTable(path);
if (this.iRecordingID == tbl.Length())
{
string[] strValues = new string[tbl.Width() - 1];
strValues[clsLoanRecording.LoanIDColumn - 1] = this.iLoanID.ToString();
strValues[clsLoanRecording.BookColumn - 1] = this.iBook.ToString();
strValues[clsLoanRecording.PageColumn - 1] = this.iPage.ToString();
strValues[clsLoanRecording.InstrumentColumn - 1] = this.iInstrument.ToString();
strValues[clsLoanRecording.ParcelColumn - 1] = this.iParcel.ToString();
strValues[clsLoanRecording.RecordingDateColumn - 1] = this.dtRecording.ToString();
tbl.New(strValues);
return tbl.Save();
}
else
{
if ((this.iRecordingID < tbl.Length()) && (this.iRecordingID >= 0))
{
if (
tbl.Update(this.iRecordingID, clsLoanRecording.LoanIDColumn, this.iLoanID.ToString()) &&
tbl.Update(this.iRecordingID, clsLoanRecording.BookColumn, this.iBook.ToString()) &&
tbl.Update(this.iRecordingID, clsLoanRecording.PageColumn, this.iPage.ToString()) &&
tbl.Update(this.iRecordingID, clsLoanRecording.InstrumentColumn, this.iInstrument.ToString()) &&
tbl.Update(this.iRecordingID, clsLoanRecording.ParcelColumn, this.iParcel.ToString()) &&
tbl.Update(this.iRecordingID, clsLoanRecording.RecordingDateColumn, this.iRecordingID.ToString()))
{
return tbl.Save();
}
else
{
return false;
}
}
else
{
return false;
}
}
}
public bool Save()
{
return this.Save(clsLoanRecording.strLoanRecordingPath);
}
#endregion
#region Private Methods
private bool _LoadByAddress(string a, clsCSVTable tbl)
{
this.iLoanID = clsLoan.LoanID(a);
if (this.iLoanID < 0)
{
this.init();
return false;
}
else
{
List<int> matches = tbl.Matches(clsLoanRecording.LoanIDColumn, this.iLoanID.ToString());
if (matches.Count == 0)
{
this.init();
return false;
}
else
{
this._Load(matches[0], tbl);
}
}
return true;
}
private bool _Load(int loanRecordingID, clsCSVTable tbl)
{
this.iRecordingID = loanRecordingID;
if (loanRecordingID < tbl.Length())
{
this.iRecordingID = Int32.Parse(tbl.Value(loanRecordingID, clsLoanRecording.IndexColumn));
this.iBook = Int32.Parse(tbl.Value(loanRecordingID, clsLoanRecording.BookColumn));
this.iPage = Int32.Parse(tbl.Value(loanRecordingID, clsLoanRecording.PageColumn));
this.iInstrument = Int32.Parse(tbl.Value(loanRecordingID, clsLoanRecording.InstrumentColumn));
this.iParcel = Int32.Parse(tbl.Value(loanRecordingID, clsLoanRecording.ParcelColumn));
this.dtRecording = DateTime.Parse(tbl.Value(loanRecordingID, clsLoanRecording.RecordingDateColumn));
return true;
}
else return false;
}
private void init()
{
this.iRecordingID = -1;
this.iLoanID = -1;
this.iBook = -1;
this.iPage = -1;
this.iInstrument = -1;
this.iParcel = -1;
this.dtRecording = System.DateTime.MaxValue;
}
private int _NewLoanRecordingID(clsCSVTable tbl)
{
return tbl.Length();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using GameData;
namespace ShootingGame.Data
{
public class GameWorldData
{
public GameWorldData(WorldMatrix matrix) {
this.boundryLeft = matrix.boundryLeft;
this.boundryRight = matrix.boundryRight;
this.boundryNear = matrix.boundryNear;
this.boundryFar = matrix.boundryFar;
this.FLYING_OUT_ZONE = matrix.FLYING_OUT_ZONE;
this.PLAYER_BULLET_SPEED = matrix.PLAYER_BULLET_SPEED;
this.OCTREE_WORLD_CENTER = new Vector3(matrix.OCTREE_WORLD_CENTER_X, 0, matrix.OCTREE_WORLD_CENTER_Z);
this.OCTREE_WORLD_SIZE = matrix.OCTREE_WORLD_SIZE;
}
private int boundryLeft ;
public int BoundryLeft
{
get { return boundryLeft; }
}
private int boundryRight ;
public int BoundryRight
{
get { return boundryRight; }
}
private int boundryNear;
public int BoundryNear
{
get { return boundryNear; }
}
private int boundryFar ;
public int BoundryFar
{
get { return boundryFar; }
}
private int FLYING_OUT_ZONE ;
public int FLYING_OUT_ZONE1
{
get { return FLYING_OUT_ZONE; }
}
private int PLAYER_BULLET_SPEED;
public int PLAYER_BULLET_SPEED1
{
get { return PLAYER_BULLET_SPEED; }
}
private Vector3 OCTREE_WORLD_CENTER ;
public Vector3 OCTREE_WORLD_CENTER1
{
get { return OCTREE_WORLD_CENTER; }
}
private int OCTREE_WORLD_SIZE;
public int OCTREE_WORLD_SIZE1
{
get { return OCTREE_WORLD_SIZE; }
}
}
}
|
using OnboardingSIGDB1.Domain._Base;
using System;
namespace OnboardingSIGDB1.Domain.Funcionarios.Specifications
{
public class ListarFuncionarioSpecificationBuilder : SpecificationBuilder<Funcionario>
{
private long _id;
private string _nome;
private string _cpf;
private DateTime? _dataContratacaoInicio;
private DateTime? _dataContratacaoFim;
public static ListarFuncionarioSpecificationBuilder Novo()
{
return new ListarFuncionarioSpecificationBuilder();
}
public ListarFuncionarioSpecificationBuilder ComId(long id)
{
_id = id;
return this;
}
public ListarFuncionarioSpecificationBuilder ComNome(string nome)
{
_nome = nome;
return this;
}
public ListarFuncionarioSpecificationBuilder ComCpf(string cpf)
{
_cpf = cpf;
return this;
}
public ListarFuncionarioSpecificationBuilder ComDataContratacaoInicio(DateTime? dataFundacaoInicio)
{
_dataContratacaoInicio = dataFundacaoInicio;
return this;
}
public ListarFuncionarioSpecificationBuilder ComDataContratacaoFim(DateTime? dataFundacaoFim)
{
_dataContratacaoFim = dataFundacaoFim;
return this;
}
public override Specification<Funcionario> Build()
{
return new Specification<Funcionario>(func =>
(_id == 0 || func.Id == _id) &&
(string.IsNullOrEmpty(_nome) || func.Nome.ToUpper().Contains(_nome)) &&
(string.IsNullOrEmpty(_cpf) || func.Cpf.Equals(_cpf)) &&
(!_dataContratacaoInicio.HasValue || (func.DataContratacao.HasValue && func.DataContratacao.Value.Date >= _dataContratacaoInicio.Value.Date)) &&
(!_dataContratacaoFim.HasValue || (func.DataContratacao.HasValue && func.DataContratacao.Value.Date <= _dataContratacaoFim.Value.Date))
)
.OrderBy(OrdenarPor)
.Paging(Pagina)
.PageSize(TamanhoDaPagina);
}
}
}
|
using BDTest.Test;
using Newtonsoft.Json;
namespace BDTest.Helpers.JsonConverters;
internal class StoryTextConverter : JsonConverter<StoryText>
{
public override void WriteJson(JsonWriter writer, StoryText value, JsonSerializer serializer)
{
if (value == null)
{
return;
}
writer.WriteValue(value.Story);
}
public override StoryText ReadJson(JsonReader reader, Type objectType, StoryText existingValue,
bool hasExistingValue, JsonSerializer serializer)
{
return new StoryText(reader.Value?.ToString());
}
}
|
namespace pPsh.Models
{
public class ScenarioEmail
{
public int ID { get; set; }
public int ScenarioID { get; set; }
public virtual Scenario Scenario { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public string RecipientAddress { get; set; }
}
}
|
namespace aairvid
{
public interface IVideoNotPlayableListener
{
void OnVideoNotPlayable();
}
}
|
using Photon.Pun;
using Photon.Realtime;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace PhotonTutorial.Menus
{
public class MainMenu : MonoBehaviourPunCallbacks
{
// Panel References to activate/deactivate when connected
[SerializeField]
private GameObject startScreen = null;
[SerializeField]
private GameObject nameInput = null;
[SerializeField]
private GameObject mainMenu = null;
[SerializeField]
private Button playButton = null;
[SerializeField]
private GameObject connectingText = null;
// Key to hold user's name
private const string PlayerPrefsNameKey = "PlayerName";
// Game version to prevent different game versions from playing together
private const string GameVersion = "1.3";
private void Awake() => PhotonNetwork.AutomaticallySyncScene = true;
void Start()
{
// if user is not connected start connecting
if (!PhotonNetwork.IsConnected)
{
PhotonNetwork.ConnectUsingSettings();
PhotonNetwork.GameVersion = GameVersion;
// if player is not first time user, get last username and ignore PLAY button (used on first time load up only)
if (PlayerPrefs.HasKey(PlayerPrefsNameKey))
{
playButton.gameObject.SetActive(false);
connectingText.SetActive(true);
}
}
else
{
startScreen.SetActive(false);
mainMenu.SetActive(true);
}
}
// Called when the player has successfully connected to the master server
public override void OnConnectedToMaster()
{
// If the start screen is active (e.g. you just started up the game, and you're not reconnecting from leaving a room)
if (startScreen.activeSelf)
{
Debug.Log("Connected to Photon server");
playButton.interactable = true;
// Try to get players username if it exists
if (PlayerPrefs.HasKey(PlayerPrefsNameKey))
{
SavePlayerName();
mainMenu.SetActive(true);
startScreen.SetActive(false);
}
}
else if (!PhotonNetwork.InLobby)
{
PhotonNetwork.JoinLobby(); //Join lobby after reconnecting from leaving a room
}
}
// Move to name input screen from start screen
public void Play()
{
startScreen.SetActive(false);
nameInput.SetActive(true);
}
public void OnClick_Quit()
{
Application.Quit();
}
// Saving player name from previous gameplay session
private void SavePlayerName()
{
string playerName = PlayerPrefs.GetString(PlayerPrefsNameKey);
PhotonNetwork.NickName = playerName;
PlayerPrefs.SetString(PlayerPrefsNameKey, playerName);
if (!PhotonNetwork.InLobby)
{
PhotonNetwork.JoinLobby(); //Join lobby after entering username so that the lobby's room list is immediately updated with correct rooms
}
}
public override void OnJoinedLobby()
{
Debug.Log("Connected to Photon LOBBY");
}
public override void OnDisconnected(DisconnectCause cause)
{
Debug.Log("Disconnected due to: " + cause);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Windows.Controls;
//------------------------------------------------
// Grant limited access to Azure Storage resources using shared access signatures (SAS) - Next Steps
// https://docs.microsoft.com/en-gb/azure/storage/common/storage-sas-overview
//------------------------------------------------
// Service SAS examples:
// https://docs.microsoft.com/en-us/rest/api/storageservices/service-sas-examples
//------------------------------------------------
namespace Storage_Helper_SAS_Tool
{
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
// Service SAS
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
class Service
{
//---------------------------------------------------------------------------------------------------------------------
//-------------------- Container Snapshot Service SAS
//---------------------------------------------------------------------------------------------------------------------
public static bool Regenerate_ServiceSAS_Container(TextBox BoxAuthResults, string VersionControl, bool debug = false)
{
string sas = "?" + Manual_ServiceSas(VersionControl, debug);
if (sas == "?") return false;
BoxAuthResults.Text = "\n\n";
BoxAuthResults.Text += "WARNING:\n";
BoxAuthResults.Text += " Different order on parameter values (ex: ss=bfq vs ss=bqf) may generate different valid signature (sig)\n";
BoxAuthResults.Text += "\n";
BoxAuthResults.Text += "Regenerated Service SAS - Container:\n";
BoxAuthResults.Text += Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += sas + "\n\n";
BoxAuthResults.Text += SAS_Utils.SAS.DebugInfo + "\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Container URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + sas + "\n\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Test your SAS on Browser (list blobs):\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + "?restype=container&comp=list" + Uri.UnescapeDataString(sas).Replace("?", "&") + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + "?restype=container&comp=list" + sas.Replace("?", "&") + "\n\n";
return true;
}
//---------------------------------------------------------------------------------------------------------------------
//-------------------- Blob Service SAS
//---------------------------------------------------------------------------------------------------------------------
public static bool Regenerate_ServiceSAS_Blob(TextBox BoxAuthResults, string VersionControl, bool debug = false)
{
string sas = "?" + Manual_ServiceSas(VersionControl, debug);
if (sas == "?") return false;
BoxAuthResults.Text = "\n\n";
BoxAuthResults.Text += "WARNING:\n";
BoxAuthResults.Text += " Different order on parameter values (ex: ss=bfq vs ss=bqf) may generate different valid signature (sig)\n";
BoxAuthResults.Text += "\n";
BoxAuthResults.Text += "Regenerated Service SAS - Blob:\n";
BoxAuthResults.Text += Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += sas + "\n\n";
BoxAuthResults.Text += SAS_Utils.SAS.DebugInfo + "\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Blob URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + "/" + SAS_Utils.SAS.blobName.v + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + "/" + SAS_Utils.SAS.blobName.v + sas + "\n\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Test your SAS on Browser (get blob):\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + "/" + SAS_Utils.SAS.blobName.v + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + "/" + SAS_Utils.SAS.blobName.v + sas + "\n\n";
return true;
}
//---------------------------------------------------------------------------------------------------------------------
//-------------------- Blob Snapshot Service SAS
//---------------------------------------------------------------------------------------------------------------------
public static bool Regenerate_ServiceSAS_BlobSnapshot(TextBox BoxAuthResults, string VersionControl, bool debug = false)
{
string sas = "?" + Manual_ServiceSas(VersionControl, debug);
if (sas == "?") return false;
BoxAuthResults.Text = "\n\n";
BoxAuthResults.Text += "WARNING:\n";
BoxAuthResults.Text += " Different order on parameter values (ex: ss=bfq vs ss=bqf) may generate different valid signature (sig)\n";
BoxAuthResults.Text += "\n";
BoxAuthResults.Text += "Regenerated Service SAS - Blob Snapshot:\n";
BoxAuthResults.Text += Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += sas + "\n\n";
BoxAuthResults.Text += SAS_Utils.SAS.DebugInfo + "\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Blob Snapshot URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + "/" + SAS_Utils.SAS.blobSnapshotName.v + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + "/" + SAS_Utils.SAS.blobSnapshotName.v + sas + "\n\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Test your SAS on Browser (get snapshot) (repalce <DateTime> by snapshot datetime):\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + "/" + SAS_Utils.SAS.blobSnapshotName.v + "?snapshot=<DateTime>" + Uri.UnescapeDataString(sas).Replace("?", "&") + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + SAS_Utils.SAS.containerName.v + "/" + SAS_Utils.SAS.blobSnapshotName.v /* + "?snapshot=<DateTime>" */ + sas + "\n\n";
return true;
}
//---------------------------------------------------------------------------------------------------------------------
//-------------------- Share Service SAS
//---------------------------------------------------------------------------------------------------------------------
public static bool Regenerate_ServiceSAS_Share(TextBox BoxAuthResults, string VersionControl, bool debug = false)
{
string sas = "?" + Manual_ServiceSas(VersionControl, debug);
if (sas == "?") return false;
BoxAuthResults.Text = "\n\n";
BoxAuthResults.Text += "WARNING:\n";
BoxAuthResults.Text += " Different order on parameter values (ex: ss=bfq vs ss=bqf) may generate different valid signature (sig)\n";
BoxAuthResults.Text += "\n";
BoxAuthResults.Text += "Regenerated Service SAS - Share:\n";
BoxAuthResults.Text += Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += sas + "\n\n";
BoxAuthResults.Text += SAS_Utils.SAS.DebugInfo + "\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Share URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".file.core.windows.net/" + SAS_Utils.SAS.shareName.v + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".file.core.windows.net/" + SAS_Utils.SAS.shareName.v + sas + "\n\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Test your SAS on Browser (list files):\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".file.core.windows.net/" + SAS_Utils.SAS.shareName.v + "?restype=directory&comp=list" + Uri.UnescapeDataString(sas).Replace("?", "&") + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".file.core.windows.net/" + SAS_Utils.SAS.shareName.v + "?restype=directory&comp=list" + sas.Replace("?", "&") + "\n\n";
return true;
}
//---------------------------------------------------------------------------------------------------------------------
//-------------------- File Service SAS
//---------------------------------------------------------------------------------------------------------------------
public static bool Regenerate_ServiceSAS_File(TextBox BoxAuthResults, string VersionControl, bool debug = false)
{
string sas = "?" + Manual_ServiceSas(VersionControl, debug);
if (sas == "?") return false;
BoxAuthResults.Text = "\n\n";
BoxAuthResults.Text += "WARNING:\n";
BoxAuthResults.Text += " Different order on parameter values (ex: ss=bfq vs ss=bqf) may generate different valid signature (sig)\n";
BoxAuthResults.Text += "\n";
BoxAuthResults.Text += "Regenerated Service SAS - File:\n";
BoxAuthResults.Text += Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += sas + "\n\n";
BoxAuthResults.Text += SAS_Utils.SAS.DebugInfo + "\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "File URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".file.core.windows.net/" + SAS_Utils.SAS.shareName.v + "/" + SAS_Utils.SAS.fileName.v + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".file.core.windows.net/" + SAS_Utils.SAS.shareName.v + "/" + SAS_Utils.SAS.fileName.v + sas + "\n\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Test your SAS on Browser (get file):\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".file.core.windows.net/" + SAS_Utils.SAS.shareName.v + "/" + SAS_Utils.SAS.fileName.v + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".file.core.windows.net/" + SAS_Utils.SAS.shareName.v + "/" + SAS_Utils.SAS.fileName.v + sas + "\n\n";
return true;
}
//---------------------------------------------------------------------------------------------------------------------
//-------------------- Queue Service SAS
//---------------------------------------------------------------------------------------------------------------------
public static bool Regenerate_ServiceSAS_Queue(TextBox BoxAuthResults, string VersionControl, bool debug = false)
{
string sas = "?" + Manual_ServiceSas(VersionControl, debug);
if (sas == "?") return false;
BoxAuthResults.Text = "\n\n";
BoxAuthResults.Text += "WARNING:\n";
BoxAuthResults.Text += " Different order on parameter values (ex: ss=bfq vs ss=bqf) may generate different valid signature (sig)\n";
BoxAuthResults.Text += "\n";
BoxAuthResults.Text += "Regenerated Service SAS - Queue:\n";
BoxAuthResults.Text += Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += sas + "\n\n";
BoxAuthResults.Text += SAS_Utils.SAS.DebugInfo + "\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Queue URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".queue.core.windows.net/" + SAS_Utils.SAS.queueName.v + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".queue.core.windows.net/" + SAS_Utils.SAS.queueName.v + sas + "\n\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Test your SAS on Browser (list messages):\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".queue.core.windows.net/" + SAS_Utils.SAS.queueName.v + "/messages" + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".queue.core.windows.net/" + SAS_Utils.SAS.queueName.v + "/messages" + sas + "\n\n";
return true;
}
//---------------------------------------------------------------------------------------------------------------------
//-------------------- Table Service SAS
//---------------------------------------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <param name="labelTableName"></param>
/// <param name="textBoxAccountName"></param>
/// <param name="textBoxAccountKey1"></param>
/// <param name="textBoxTableName"></param>
/// <param name="textBoxPolicyName"></param>
/// <param name="BoxAuthResults"></param>
/// <returns></returns>
public static bool Regenerate_ServiceSAS_Table(TextBox BoxAuthResults, string VersionControl, bool debug = false)
{
string sas = "?" + Manual_ServiceSas(VersionControl, debug);
if (sas == "?") return false;
BoxAuthResults.Text = "\n\n";
BoxAuthResults.Text += "WARNING:\n";
BoxAuthResults.Text += " Different order on parameter values (ex: ss=bfq vs ss=bqf) may generate different valid signature (sig)\n";
BoxAuthResults.Text += "\n";
BoxAuthResults.Text = "Regenerated Service SAS - Table:\n";
BoxAuthResults.Text += Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += sas + "\n\n";
BoxAuthResults.Text += SAS_Utils.SAS.DebugInfo + "\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Table URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".table.core.windows.net/" + SAS_Utils.SAS.tableName.v + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".table.core.windows.net/" + SAS_Utils.SAS.tn.v + sas + "\n\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Test your SAS on Browser (list entities):\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".table.core.windows.net/" + SAS_Utils.SAS.tableName.v + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".table.core.windows.net/" + SAS_Utils.SAS.tn.v + sas + "\n\n";
return true;
}
/// <summary>
/// Regenerate Service Generic SAS without SDK
/// </summary>
/// <param name="VersionControl - Usualy sv (Service Version) used to generate the Account SAS"></param>
/// <param name="debug - Degub mode (true) - Show Canonical-Path-to-Resource and String-to-Sign used to generate the Account SAS"></param>
/// <returns>Generated Account SAS without starting '?'</returns>
public static string Manual_ServiceSas(string VersionControl, bool debug = false)
{
if (String.Compare(SAS_Utils.SAS.spr.v.ToLower(), "http") == 0) return "'HTTP' ONLY IS NOT SUPPORTED AS SIGNED PROTOCOL";
string signature = string.Empty;
string canonicalPathToResource = string.Empty;
string stringtosign;
string s = "";
//-------------------------------------------------------------------------------------
// Ordering permissions - racwudpl
SAS_Utils.SAS.sp.v = SAS_Utils.Order_permissions(SAS_Utils.SAS.sp.v);
//-------------------------------------------------------------------------------------
switch (SAS_Utils.SAS.sr.v)
{
case "b": // blob
canonicalPathToResource = Get_Service_canonicalPathToResource(VersionControl, SAS_Utils.SAS.sr.v);
stringtosign = Get_Service_stringtosign(VersionControl, SAS_Utils.SAS.sr.v, canonicalPathToResource);
break;
case "bs": // blob snapshot
canonicalPathToResource = Get_Service_canonicalPathToResource(VersionControl, SAS_Utils.SAS.sr.v);
stringtosign = Get_Service_stringtosign(VersionControl, SAS_Utils.SAS.sr.v, canonicalPathToResource);
break;
case "c": // container
canonicalPathToResource = Get_Service_canonicalPathToResource(VersionControl, SAS_Utils.SAS.sr.v);
stringtosign = Get_Service_stringtosign(VersionControl, SAS_Utils.SAS.sr.v, canonicalPathToResource);
break;
case "f": // file
canonicalPathToResource = Get_Service_canonicalPathToResource(VersionControl, SAS_Utils.SAS.sr.v);
stringtosign = Get_Service_stringtosign(VersionControl, SAS_Utils.SAS.sr.v, canonicalPathToResource);
break;
case "s": // share
canonicalPathToResource = Get_Service_canonicalPathToResource(VersionControl, SAS_Utils.SAS.sr.v);
stringtosign = Get_Service_stringtosign(VersionControl, SAS_Utils.SAS.sr.v, canonicalPathToResource);
break;
default:
if (!String.IsNullOrEmpty(SAS_Utils.SAS.tn.v)) // table
{
canonicalPathToResource = Get_Service_canonicalPathToResource(VersionControl, "t");
stringtosign = Get_Service_stringtosign(VersionControl, "t", canonicalPathToResource); // queue dont have 'sr', but table name on 'tn'
}
else // queue
{
canonicalPathToResource = Get_Service_canonicalPathToResource(VersionControl, "q");
stringtosign = Get_Service_stringtosign(VersionControl, "q", canonicalPathToResource); // queue dont have 'sr'
}
break;
}
//-------------------------------------------------------------------------------------
//Get a reference to a blob within the container.
byte[] keyForSigning = System.Convert.FromBase64String(SAS_Utils.SAS.storageAccountKey.v.Trim());
using (var hmac = new HMACSHA256(keyForSigning))
{
signature = System.Convert.ToBase64String(
hmac.ComputeHash(Encoding.UTF8.GetBytes(stringtosign))
);
}
//-------------------------------------------------------------------------------------
string sharedAccessSignature = "";
sharedAccessSignature += SAS_Utils.Get_Parameter("sv", VersionControl);
sharedAccessSignature += SAS_Utils.Get_Parameter("sr", SAS_Utils.SAS.sr.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("st", SAS_Utils.SAS.st.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("se", SAS_Utils.SAS.se.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("sp", SAS_Utils.SAS.sp.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("sip", SAS_Utils.SAS.sip.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("spr", SAS_Utils.SAS.spr.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("si", SAS_Utils.SAS.si.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("sig", signature);
// Remove the first "&"
sharedAccessSignature = sharedAccessSignature.TrimStart('&');
SAS_Utils.SAS.sig = Uri.UnescapeDataString(SAS_Utils.Get_SASValue(sharedAccessSignature, "sig=", "&"));
//-------------------------------------------------------------------------------------
if (debug)
{
SAS_Utils.SAS.DebugInfo = "\n";
SAS_Utils.SAS.DebugInfo += "------ Debug Info ----------" + "\n";
SAS_Utils.SAS.DebugInfo += "Canonical-Path-to-Resource: " + canonicalPathToResource + "\n";
SAS_Utils.SAS.DebugInfo += "---------------------------" + "\n";
SAS_Utils.SAS.DebugInfo += "String-to-Sign: \n" + stringtosign;
SAS_Utils.SAS.DebugInfo += "---------------------------" + "\n";
}
else
SAS_Utils.SAS.DebugInfo = "";
return string.Format(sharedAccessSignature + s);
}
/// <summary>
///
/// </summary>
/// <param name="VersionControl"></param>
/// <returns></returns>
private static string Get_Service_canonicalPathToResource(string VersionControl, string signedresource)
{
if (String.Compare(VersionControl, "2015-02-21") >= 0)
switch (signedresource)
{
case "b": // blob
return ("/blob/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.containerName.v.Trim() + "/" + SAS_Utils.SAS.blobName.v.Trim()).Trim();
case "bs": // blob Snapshot - canonicalizedresource not documented
return ("/blob/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.containerName.v.Trim() + "/" + SAS_Utils.SAS.blobName.v.Trim()).Trim();
case "c": // container
return ("/blob/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.containerName.v.Trim()).Trim();
case "f": // file
return ("/file/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.shareName.v.Trim() + "/" + SAS_Utils.SAS.fileName.v.Trim()).Trim();
case "s": // share
return ("/file/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.shareName.v.Trim()).Trim();
case "t": // table
return ("/table/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.tn.v.Trim()).Trim();
case "q": // queue
return ("/queue/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.queueName.v.Trim()).Trim();
}
else
switch (signedresource)
{
case "b": // blob
return ("/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.containerName.v.Trim() + "/" + SAS_Utils.SAS.blobName.v.Trim()).Trim();
case "c": // container
return ("/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.containerName.v.Trim()).Trim();
case "f": // file
return ("/file/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.shareName.v.Trim() + "/" + SAS_Utils.SAS.fileName.v.Trim()).Trim();
case "s": // share
return ("/file/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.shareName.v.Trim()).Trim();
case "t": // table
return ("/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.tn.v.Trim()).Trim();
case "q": // queue
return ("/" + SAS_Utils.SAS.storageAccountName.v.Trim() + "/" + SAS_Utils.SAS.queueName.v.Trim()).Trim();
}
return "CanonicalPathToResource NOT SUPPORTED FOR THIS RESOURCE ON THIS SERVICE VERSION. signedresource: " + signedresource + " VersionControl: " + VersionControl; // something else not supported
}
/// <summary>
///
/// </summary>
/// <param name="VersionControl"></param>
/// <param name="sStartTime"></param>
/// <param name="sExpiryTime"></param>
/// <param name="canonicalPathToResource"></param>
/// <returns></returns>
private static string Get_Service_stringtosign(string VersionControl, string signedresource, string canonicalPathToResource)
{
// adds support for the signed resource and signed blob snapshot time fields
// for Blob service resources, use the following format:
if (String.Compare(VersionControl, "2018-11-09") >= 0)
return SAS_Utils.SAS.sp.v + "\n" +
SAS_Utils.SAS.st.v + "\n" +
SAS_Utils.SAS.se.v + "\n" +
canonicalPathToResource + "\n" +
SAS_Utils.SAS.si.v + "\n" +
SAS_Utils.SAS.sip.v + "\n" +
SAS_Utils.SAS.spr.v + "\n" +
SAS_Utils.SAS.sv.v + "\n" +
signedresource + "\n" +
SAS_Utils.SAS.blobSnapshotTime.v + "\n" +
SAS_Utils.SAS.rscc + "\n" +
SAS_Utils.SAS.rscd + "\n" +
SAS_Utils.SAS.rsce + "\n" +
SAS_Utils.SAS.rscl + "\n" +
SAS_Utils.SAS.rsct;
// adds support for the signed IP and signed protocol fields
if (String.Compare(VersionControl, "2015-04-05") >= 0)
switch (signedresource)
{
// for Blob or File service resources, use the following format:
case "b": // blob
case "f": // file
case "c": // container - same stringtosign ???
case "s": // share - same stringtosign ???
return SAS_Utils.SAS.sp.v + "\n" +
SAS_Utils.SAS.st.v + "\n" +
SAS_Utils.SAS.se.v + "\n" +
canonicalPathToResource + "\n" +
SAS_Utils.SAS.si.v + "\n" +
SAS_Utils.SAS.sip.v + "\n" +
SAS_Utils.SAS.spr.v + "\n" +
SAS_Utils.SAS.sv.v + "\n" +
SAS_Utils.SAS.rscc + "\n" +
SAS_Utils.SAS.rscd + "\n" +
SAS_Utils.SAS.rsce + "\n" +
SAS_Utils.SAS.rscl + "\n" +
SAS_Utils.SAS.rsct;
// for Table service resources, use the following format:
case "t": // table
return SAS_Utils.SAS.sp.v + "\n" +
SAS_Utils.SAS.st.v + "\n" +
SAS_Utils.SAS.se.v + "\n" +
canonicalPathToResource + "\n" +
SAS_Utils.SAS.si.v + "\n" +
SAS_Utils.SAS.sip.v + "\n" +
SAS_Utils.SAS.spr.v + "\n" +
SAS_Utils.SAS.sv.v + "\n" +
SAS_Utils.SAS.spk + "\n" +
SAS_Utils.SAS.srk + "\n" +
SAS_Utils.SAS.epk + "\n" +
SAS_Utils.SAS.erk;
// for Queue service resources, use the following format:
case "q": // queue
return SAS_Utils.SAS.sp.v + "\n" +
SAS_Utils.SAS.st.v + "\n" +
SAS_Utils.SAS.se.v + "\n" +
canonicalPathToResource + "\n" +
SAS_Utils.SAS.si.v + "\n" +
SAS_Utils.SAS.sip.v + "\n" +
SAS_Utils.SAS.spr.v + "\n" +
SAS_Utils.SAS.sv.v;
}
if (String.Compare(VersionControl, "2013-08-15") >= 0) // 2013-08-15 through version 2015-02-21
switch (signedresource)
{
// for Blob or File service resources using the 2013-08-15 version through version 2015-02-21, use the following format.
// Note that for the File service, SAS is supported beginning with version 2015-02-21
case "b": // blob
case "f": // file
case "c": // container - same stringtosign ???
case "s": // share - same stringtosign ???
if ((signedresource == "f" || signedresource == "s") && VersionControl != "2015-02-21")
return ""; // File service, SAS is supported beginning with version 2015-02-21
else
return SAS_Utils.SAS.sp.v + "\n" +
SAS_Utils.SAS.st.v + "\n" +
SAS_Utils.SAS.se.v + "\n" +
canonicalPathToResource + "\n" +
SAS_Utils.SAS.si.v + "\n" +
SAS_Utils.SAS.sv.v + "\n" +
SAS_Utils.SAS.rscc + "\n" +
SAS_Utils.SAS.rscd + "\n" +
SAS_Utils.SAS.rsce + "\n" +
SAS_Utils.SAS.rscl + "\n" +
SAS_Utils.SAS.rsct;
// for Table service resources, use the following format:
case "t": // table
return SAS_Utils.SAS.sp.v + "\n" +
SAS_Utils.SAS.st.v + "\n" +
SAS_Utils.SAS.se.v + "\n" +
canonicalPathToResource + "\n" +
SAS_Utils.SAS.si.v + "\n" +
SAS_Utils.SAS.sv.v + "\n" +
SAS_Utils.SAS.spk + "\n" +
SAS_Utils.SAS.srk + "\n" +
SAS_Utils.SAS.epk + "\n" +
SAS_Utils.SAS.erk;
// for Queue service resources, use the following format:
case "q": // queue
return SAS_Utils.SAS.sp.v + "\n" +
SAS_Utils.SAS.st.v + "\n" +
SAS_Utils.SAS.se.v + "\n" +
canonicalPathToResource + "\n" +
SAS_Utils.SAS.si.v + "\n" +
SAS_Utils.SAS.sv.v;
}
// for Blob service resources for version 2012-02-12, use the following format:
if (VersionControl == "2012-02-12")
switch (signedresource)
{
case "b": // blob
case "c": // container - same stringtosign ???
return SAS_Utils.SAS.sp.v + "\n" +
SAS_Utils.SAS.st.v + "\n" +
SAS_Utils.SAS.se.v + "\n" +
canonicalPathToResource + "\n" +
SAS_Utils.SAS.si.v + "\n" +
SAS_Utils.SAS.sv.v;
}
// for Blob service resources for versions prior to 2012-02-12, use the following format:
if (String.Compare(VersionControl, "2012-02-12") < 0)
switch (signedresource)
{
case "b": // blob
case "c": // container - same stringtosign ???
return SAS_Utils.SAS.sp.v + "\n" +
SAS_Utils.SAS.st.v + "\n" +
SAS_Utils.SAS.se.v + "\n" +
canonicalPathToResource + "\n" +
SAS_Utils.SAS.si.v;
}
return "String-To-Sign NOT SUPPORTED FOR THIS RESOURCE ON THIS SERVICE VERSION. signedresource: " + signedresource + " VersionControl: " + VersionControl; // something else not supported
}
}
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
// Account SAS
//-------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------
class Account
{
/// <summary>
/// Regenerate Account SAS without SDK, based on ss (Signed Services) parameter
/// </summary>
/// <param name="BoxAuthResults - Graphic Text Box to show the results"></param>
/// <param name="VersionControl - Usualy sv (Service Version) used to generate the Account SAS"></param>
/// <param name="debug - Degub mode (true) - Show Canonical-Path-to-Resource and String-to-Sign used to generate the Account SAS"></param>
/// <returns></returns>
public static bool Regenerate_AccountSAS(TextBox BoxAuthResults, string VersionControl, bool debug = false)
{
string sas = "?" + Manual_AccountSas(VersionControl, debug);
if (sas == "?") return false;
BoxAuthResults.Text = "\n\n";
BoxAuthResults.Text += "WARNING:\n";
BoxAuthResults.Text += " Different order on parameter values (ex: ss=bfq vs ss=bqf) may generate different valid signature (sig)\n";
BoxAuthResults.Text += "\n";
BoxAuthResults.Text += "Regenerated Account SAS token:\n";
BoxAuthResults.Text += Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += sas + "\n\n";
BoxAuthResults.Text += SAS_Utils.SAS.DebugInfo + "\n";
BoxAuthResults.Text += "-------------------------------------------------\n";
if (SAS_Utils.SAS.ss.v.IndexOf("b") != -1)
{
BoxAuthResults.Text += "Blob URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/" + sas + "\n\n";
}
if (SAS_Utils.SAS.ss.v.IndexOf("f") != -1)
{
BoxAuthResults.Text += "File URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".file.core.windows.net/" + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".file.core.windows.net/" + sas + "\n\n";
}
if (SAS_Utils.SAS.ss.v.IndexOf("q") != -1)
{
BoxAuthResults.Text += "Queue URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".queue.core.windows.net/" + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".queue.core.windows.net/" + sas + "\n\n";
}
if (SAS_Utils.SAS.ss.v.IndexOf("t") != -1)
{
BoxAuthResults.Text += "Table URI:\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".table.core.windows.net/" + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".table.core.windows.net/" + sas + "\n\n";
}
BoxAuthResults.Text += "-------------------------------------------------\n";
BoxAuthResults.Text += "Test your SAS on Browser (get blob) (replace <container> and <blob>):\n";
//BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/<container>/<blob>" + Uri.UnescapeDataString(sas) + "\n";
BoxAuthResults.Text += "https://" + SAS_Utils.SAS.storageAccountName.v + ".blob.core.windows.net/<container>/<blob>" + sas + "\n\n";
return true;
}
/// <summary>
/// Regenerate Account SAS without SDK
/// </summary>
/// <param name="VersionControl - Usualy sv (Service Version) used to generate the Account SAS"></param>
/// <param name="debug - Degub mode (true) - Show Canonical-Path-to-Resource and String-to-Sign used to generate the Account SAS"></param>
/// <returns>Generated Account SAS without starting '?'</returns>
public static string Manual_AccountSas(string VersionControl, bool debug = false)
{
if (String.Compare(VersionControl, "2015-04-05") < 0) return "ACCOUNT SAS ONLY SUPPORTS SERVICE VERSION BEGINING AT 2015-04-05";
if (String.Compare(SAS_Utils.SAS.spr.v.ToLower(), "http") == 0) return "'HTTP' ONLY IS NOT SUPPORTED AS SIGNED PROTOCOL";
string signature = string.Empty;
string s = "";
//-------------------------------------------------------------------------------------
// Ordering permissions only on Service SAS - Account SAS uses the same order as on ComboBox
// SAS_Utils.SAS.sp.v = RestAPI.Order_permissions(SAS_Utils.SAS.sp.v);
//-------------------------------------------------------------------------------------
string stringtosign = SAS_Utils.SAS.storageAccountName.v.Trim() + "\n" +
SAS_Utils.SAS.sp.v + "\n" +
SAS_Utils.SAS.ss.v + "\n" +
SAS_Utils.SAS.srt.v + "\n" +
SAS_Utils.SAS.st.v + "\n" +
SAS_Utils.SAS.se.v + "\n" +
SAS_Utils.SAS.sip.v + "\n" +
SAS_Utils.SAS.spr.v + "\n" +
SAS_Utils.SAS.sv.v + "\n";
//-------------------------------------------------------------------------------------
byte[] keyForSigning = System.Convert.FromBase64String(SAS_Utils.SAS.storageAccountKey.v.Trim());
using (var hmac = new HMACSHA256(keyForSigning))
{
signature = System.Convert.ToBase64String(
hmac.ComputeHash(Encoding.UTF8.GetBytes(stringtosign))
);
}
//-------------------------------------------------------------------------------------
string sharedAccessSignature = "";
sharedAccessSignature += SAS_Utils.Get_Parameter("sv", SAS_Utils.SAS.sv.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("ss", SAS_Utils.SAS.ss.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("srt", SAS_Utils.SAS.srt.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("st", SAS_Utils.SAS.st.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("se", SAS_Utils.SAS.se.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("sp", SAS_Utils.SAS.sp.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("sip", SAS_Utils.SAS.sip.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("spr", SAS_Utils.SAS.spr.v);
sharedAccessSignature += SAS_Utils.Get_Parameter("sig", signature);
// Remove the first "&"
sharedAccessSignature = sharedAccessSignature.TrimStart('&');
SAS_Utils.SAS.sig = Uri.UnescapeDataString(SAS_Utils.Get_SASValue(sharedAccessSignature, "sig=", "&"));
//-------------------------------------------------------------------------------------
if (debug)
{
SAS_Utils.SAS.DebugInfo = "\n";
SAS_Utils.SAS.DebugInfo += "------ Debug Info ----------" + "\n";
SAS_Utils.SAS.DebugInfo += "String-to-Sign: \n" + stringtosign;
SAS_Utils.SAS.DebugInfo += "---------------------------" + "\n";
}
else
SAS_Utils.SAS.DebugInfo = "";
return string.Format(sharedAccessSignature + s);
}
//-------------------------------------------------------------------
// Solution from SDK : signature = ComputeHmac256(keyForSigning, stringtosign);
// Same results, same sig
//-------------------------------------------------------------------
//https://github.com/Azure/azure-storage-net/blob/master/Lib/Common/CloudStorageAccount.cs
//https://github.com/Azure/azure-storage-net/blob/master/Lib/Common/Core/Auth/SharedAccessSignatureHelper.cs
//https://github.com/Azure/azure-storage-net/blob/master/Lib/Common/Core/Util/CryptoUtility.cs
//string signature = SharedAccessSignatureHelper.GetHash(policy, this.Credentials.AccountName, Constants.HeaderConstants.TargetStorageVersion, accountKey.KeyValue);
//UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(policy, signature, accountKey.KeyName, Constants.HeaderConstants.TargetStorageVersion);
//return builder.ToString();
internal static string ComputeHmac256(byte[] key, string message)
{
using (HashAlgorithm hashAlgorithm = new HMACSHA256(key))
{
byte[] messageBuffer = Encoding.UTF8.GetBytes(message);
return Convert.ToBase64String(hashAlgorithm.ComputeHash(messageBuffer));
}
}
//-------------------------------------------------------------------
}
}
|
using System.Collections.Generic;
using SharpArch.Domain.DomainModel;
namespace Profiling2.Domain.Prf
{
public class AdminRole : Entity
{
// TODO deprecate these constants
public const string ProfilingInternational = "ProfilingInternational";
public const string ProfilingNational = "ProfilingNational";
public const string ProfilingAdmin = "ProfilingAdmin";
public const string ProfilingLimitedPersonEdit = "ProfilingLimitedPersonEdit";
public const string ProfilingReadOnlyPersonView = "ProfilingReadOnlyPersonView";
public const string ScreeningRequestInitiator = "ScreeningRequestInitiator";
public const string ScreeningRequestValidator = "ScreeningRequestValidator";
public const string ScreeningRequestConditionalityParticipant = "ScreeningRequestConditionalityParticipant";
public const string ScreeningRequestConsolidator = "ScreeningRequestConsolidator";
public const string ScreeningRequestFinalDecider = "ScreeningRequestFinalDecider";
public virtual string Name { get; set; }
public virtual IList<AdminPermission> AdminPermissions { get; set; }
public AdminRole()
{
this.AdminPermissions = new List<AdminPermission>();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using RenderHeads.Media.AVProVideo;
public class VideoManager : MonoBehaviour
{
[SerializeField] private float uiDepth = 2.5f;
[SerializeField] private float uiDistance = 4;
[SerializeField] private MediaPlayer player;
[SerializeField] private string windowsPath;
[SerializeField] private string androidPath;
private string activePath;
[SerializeField] private GameObject cameraRigs;
[SerializeField] private OVRCameraRig ovrCameraRig;
[SerializeField] private GameObject desktopCameraRig;
[SerializeField] private GameObject videoPlayerControls;
private Vector3 cameraRigsStartPosition;
private Camera activeCamera;
private float preVideoForwardRotation;
private OVRManager VRCameraManager;
private void Awake()
{
activePath = androidPath;
var cameras = ovrCameraRig.GetComponentsInChildren<Camera>();
var cameraList = new List<Camera>(cameras);
activeCamera = cameraList.FirstOrDefault(c => c.enabled);
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
activePath = windowsPath;
activeCamera = desktopCameraRig.GetComponentInChildren<Camera>();
#endif
VRCameraManager = ovrCameraRig.GetComponent<OVRManager>();
player.Events.AddListener(OnVideoEvent);
}
private void Start()
{
cameraRigsStartPosition = cameraRigs.transform.position;
}
private void Update()
{
var heightVector = new Vector3(0, activeCamera.transform.position.y - uiDepth, 0);
var directionVector = Vector3.Normalize(Vector3.ProjectOnPlane(activeCamera.transform.forward, Vector3.up)) * uiDistance;
var cameraPosition = activeCamera.transform.position;
var newPosition = new Vector3(cameraPosition.x + directionVector.x, heightVector.y, cameraPosition.z + directionVector.z);
videoPlayerControls.transform.position = newPosition;
videoPlayerControls.transform.LookAt(activeCamera.transform);
}
public string GetActivePath()
{
return activePath;
}
public void PlayVideo(string fileName)
{
preVideoForwardRotation = activeCamera.transform.rotation.eulerAngles.y;
player.OpenVideoFromFile(MediaPlayer.FileLocation.AbsolutePathOrURL, activePath + fileName, true);
cameraRigs.transform.position = player.transform.position;
VRCameraManager.trackingOriginType = OVRManager.TrackingOrigin.EyeLevel;
videoPlayerControls.SetActive(true);
foreach (var button in FindObjectsOfType<ExperienceCard>())
{
button.Deactivate();
}
}
public void StopVideo()
{
var restoredViewDirection = new Vector3(activeCamera.transform.rotation.eulerAngles.x, preVideoForwardRotation, activeCamera.transform.rotation.eulerAngles.z);
player.Stop();
cameraRigs.transform.position = cameraRigsStartPosition;
activeCamera.transform.rotation = Quaternion.Euler(restoredViewDirection);
ovrCameraRig.trackerAnchor.rotation = Quaternion.Euler(restoredViewDirection);
VRCameraManager.trackingOriginType = OVRManager.TrackingOrigin.FloorLevel;
videoPlayerControls.SetActive(false);
}
public void OnVideoEvent(MediaPlayer mp, MediaPlayerEvent.EventType et, ErrorCode errorCode)
{
switch (et)
{
case MediaPlayerEvent.EventType.FinishedPlaying:
StopVideo();
break;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlyFloor1 : MonoBehaviour {
private Vector3 init;
public Vector3 target;
public float speed;
bool toTarget = true;
// Use this for initialization
void Start () {
init = transform.position;
}
// Update is called once per frame
void Update () {
if(toTarget)
{
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
if(transform.position == target)
toTarget = false;
}
else
{
transform.position = Vector3.MoveTowards(transform.position, init, speed * Time.deltaTime);
if (transform.position == init)
toTarget = true;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
namespace WindowsMediaPlayer
{
class MWInterface
{
private System.Drawing.Image IconMap;
public MWInterface()
{
System.Reflection.Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file = thisExe.GetManifestResourceStream("WindowsMediaPlayer.Icons.png");
if ((this.IconMap = System.Drawing.Image.FromStream(file)) == null)
throw new MWException("System.Drawing.Image.FromStream failed with parameter (" + file + ")");
}
public BitmapSource getIcon(int Index)
{
if (this.IconMap == null)
throw new MWException("The icon map has not been initialized");
int x = Convert.ToInt32(this.IconMap.Width) / 30;
int y = Convert.ToInt32(this.IconMap.Height) / 30;
int iconCount = x * y;
if (Index < 0 || Index >= iconCount) return null;
int offsetX = (Index % x) * 30;
int offsetY = (Index / x) * 30;
Bitmap bitmap = new Bitmap(30, 30);
Graphics.FromImage(bitmap).DrawImage(this.IconMap,
new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
new System.Drawing.Rectangle(offsetX, offsetY, bitmap.Width, bitmap.Height),
GraphicsUnit.Pixel);
IntPtr hbitmap = bitmap.GetHbitmap();
BitmapSource bimage = Imaging.CreateBitmapSourceFromHBitmap(
hbitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions()
);
return (bimage);
}
}
}
|
using UnityEngine;
using System.Collections;
public class WorldObjectFollower : WorldRelativeGUIElement {
GameObject objectToFollow;
RectTransform myRectTransform;
bool followeeMoves;
bool positionDirty;
public Vector3 offset = new Vector3(0, 0, 0);
public float rotation = 0;
void Start() {
// Parented by 'world' canvas.
GameObject worldCanvasGameObject = GameObject.FindWithTag ("WorldObjectCanvas");
SetParentCanvasGameObject (worldCanvasGameObject);
myRectTransform = gameObject.GetComponent <RectTransform> ();
}
// Update is called once per frame
void Update () {
if (myRectTransform) {
if (followeeMoves || positionDirty) {
positionDirty = false;
ResetPosition ();
}
}
}
public void SetObjectToFollow(GameObject go,
Vector3 offset,
bool followeeMoves = true) {
objectToFollow = go;
this.offset = offset;
this.followeeMoves = followeeMoves;
positionDirty = true;
}
public void ResetPosition() {
Vector3 canvasPosition = WorldPositionToParentCanvasPosition(
objectToFollow.transform.position);
myRectTransform.localPosition = canvasPosition + offset;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OneToMany
{
class Department
{
public Department()
{
Courses = new List<Course>();
}
public string Code { get; set; }
public string Name { get; set; }
public List<Course> Courses { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using com.Sconit.Entity.Exception;
using com.Sconit.Utility;
using Telerik.Web.Mvc;
using com.Sconit.Web.Models.SearchModels.INV;
using com.Sconit.Web.Models;
using com.Sconit.Entity.INV;
using com.Sconit.Entity.VIEW;
using com.Sconit.Entity.SCM;
using com.Sconit.Service;
using com.Sconit.Entity.MD;
using com.Sconit.Entity.ORD;
using com.Sconit.PrintModel.INV;
using AutoMapper;
using com.Sconit.Utility.Report;
using com.Sconit.Web.Models.SearchModels.BIL;
using com.Sconit.Entity.BIL;
using com.Sconit.Web.Models.SearchModels.SCM;
using com.Sconit.Web.Models.SearchModels.ORD;
using com.Sconit.Entity;
using com.Sconit.Entity.MRP.MD;
using System.Data.SqlClient;
using System.Data;
using com.Sconit.Entity.SYS;
using NHibernate;
namespace com.Sconit.Web.Controllers.INV
{
public class ContainerDetailController : WebAppBaseController
{
private static string selectCountStatement = "select count(*) from ContainerDetail as c";
private static string selectStatement = "select c from ContainerDetail as c";
public IContainerMgr containerMgr { get; set; }
#region public method
public ActionResult Index()
{
return View();
}
[SconitAuthorize(Permissions = "Url_ContainerDetail_View")]
public ActionResult New()
{
return View();
}
[HttpPost]
[SconitAuthorize(Permissions = "Url_ContainerDetail_View")]
public ActionResult New(ContainerDetail containerDetail)
{
try
{
containerMgr.CreateContainer(containerDetail.Container, containerDetail.CreateQty);
SaveSuccessMessage("容器新增成功");
return RedirectToAction("List");
}
catch (Exception ex)
{
SaveErrorMessage(ex.Message);
return View(containerDetail);
}
}
[HttpGet]
[SconitAuthorize(Permissions = "Url_ContainerDetail_View")]
public ActionResult Edit(string id)
{
if (string.IsNullOrEmpty(id))
{
return HttpNotFound();
}
else
{
ContainerDetail containerDetail = this.genericMgr.FindById<ContainerDetail>(id);
return View(containerDetail);
}
}
[GridAction]
[SconitAuthorize(Permissions = "Url_ContainerDetail_View")]
public ActionResult List(GridCommand command, ContainerDetailSearchModel searchModel)
{
SearchCacheModel searchCacheModel = this.ProcessSearchModel(command, searchModel);
if (searchCacheModel.isBack == true)
{
ViewBag.Page = searchCacheModel.Command.Page == 0 ? 1 : searchCacheModel.Command.Page;
}
ViewBag.PageSize = base.ProcessPageSize(command.PageSize);
return View();
}
[GridAction(EnableCustomBinding = true)]
[SconitAuthorize(Permissions = "Url_ContainerDetail_View")]
public ActionResult _AjaxList(GridCommand command, ContainerDetailSearchModel searchModel)
{
TempData["ContainerDetailSearchModel"] = searchModel;
this.GetCommand(ref command, searchModel);
SearchStatementModel searchStatementModel = PrepareSearchStatement(command, searchModel);
var list = GetAjaxPageData<ContainerDetail>(searchStatementModel, command);
return PartialView(list);
}
#endregion
#region private method
private SearchStatementModel PrepareSearchStatement(GridCommand command, ContainerDetailSearchModel searchModel)
{
string whereStatement = string.Empty;
IList<object> param = new List<object>();
HqlStatementHelper.AddEqStatement("ContainerId", searchModel.ContainerId, "c", ref whereStatement, param);
HqlStatementHelper.AddEqStatement("Container", searchModel.Container, "c", ref whereStatement, param);
string sortingStatement = HqlStatementHelper.GetSortingStatement(command.SortDescriptors);
if (command.SortDescriptors.Count == 0)
{
sortingStatement = " order by CreateDate desc";
}
SearchStatementModel searchStatementModel = new SearchStatementModel();
searchStatementModel.SelectCountStatement = selectCountStatement;
searchStatementModel.SelectStatement = selectStatement;
searchStatementModel.WhereStatement = whereStatement;
searchStatementModel.SortingStatement = sortingStatement;
searchStatementModel.Parameters = param.ToArray<object>();
return searchStatementModel;
}
#endregion
}
}
|
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace AttendanceWebApp.Models
{
public class Units
{
[Key, Column(Order = 0)]
[StringLength(2)]
public string CompCode { get; set; }
public virtual Company Company { get; set; }
[Key, Column(Order = 1)]
[StringLength(10)]
public string WrkGrp { get; set; }
public virtual WorkGroups WorkGroup { get; set; }
[Key, Column(Order = 2)]
[Required]
[StringLength(3)]
public string UnitCode { get; set; }
[StringLength(50)]
public string UnitName { get; set; }
[StringLength(5)]
public string Location { get; set; }
}
}
|
using AutoMapper;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Http;
using TasksApp.Models;
using TasksApp.ViewModels;
namespace TasksApp.Controllers
{
[RoutePrefix("api/account")]
public class AccountController : BaseApiController
{
protected readonly AppUserManager userManager;
protected readonly IAuthenticationManager authenticationManager;
protected readonly TasksContext dbContext;
protected readonly IMapper Mapper;
public AccountController(AppUserManager userManager,
IAuthenticationManager authenticationManager,
TasksContext dbContext,
IMapper mapper)
{
this.userManager = userManager;
this.authenticationManager = authenticationManager;
this.dbContext = dbContext;
Mapper = mapper;
}
[Route("", Name = "GetUser")]
[Authorize]
public async Task<IHttpActionResult> GetUser()
{
var userId = User.Identity.GetUserId();
var user = await userManager.FindByIdAsync(userId);
if (user == null)
{
return NotFound();
}
return Ok(Mapper.Map<UserInfoViewModel>(user));
}
[HttpPost]
[Route("register")]
public async Task<IHttpActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = Mapper.Map<AppUser>(model);
var result = await userManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result.Errors);
}
else
{
var locationHeader = Url.Link("GetUser", new { });
await SignInAsync(user);
return Created(locationHeader, Mapper.Map<UserInfoViewModel>(user));
}
}
return BadRequest(ModelState);
}
[HttpPost]
[Route("login")]
public async Task<IHttpActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var user = await userManager.FindAsync(model.Email, model.Password);
if (user == null)
{
ModelState.AddModelError("", "Wrong email and/or password");
}
else
{
await SignInAsync(user, model.RememberMe);
return Ok(Mapper.Map<UserInfoViewModel>(user));
}
}
return BadRequest(ModelState);
}
[HttpPost]
[Authorize]
[Route("logout")]
public IHttpActionResult Logout()
{
authenticationManager.SignOut();
return Ok();
}
[NonAction]
private async System.Threading.Tasks.Task SignInAsync(AppUser user, bool rememberMe = true)
{
ClaimsIdentity claim = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignOut();
authenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent = rememberMe
},
claim);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.