text stringlengths 13 6.01M |
|---|
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
namespace NtApiDotNet.Net.Firewall
{
/// <summary>
/// A builder to create a new firewall filter.
/// </summary>
public sealed class FirewallFilterBuilder : FirewallConditionBuilder
{
#region Public Properties
/// <summary>
/// The name of the filter.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The description of the filter.
/// </summary>
public string Description { get; set; }
/// <summary>
/// The filter key. If empty will be automatically assigned.
/// </summary>
public Guid FilterKey { get; set; }
/// <summary>
/// The layer key.
/// </summary>
public Guid LayerKey { get; set; }
/// <summary>
/// The sub-layer key.
/// </summary>
public Guid SubLayerKey { get; set; }
/// <summary>
/// Flags for the filter.
/// </summary>
public FirewallFilterFlags Flags { get; set; }
/// <summary>
/// Specify the initial weight.
/// </summary>
/// <remarks>You need to specify an EMPTY, UINT64 or UINT8 value.</remarks>
public FirewallValue Weight { get; set; }
/// <summary>
/// Specify the action for this filter.
/// </summary>
public FirewallActionType ActionType { get; set; }
/// <summary>
/// Specify the filter type GUID when not using a callout.
/// </summary>
public Guid FilterType { get; set; }
/// <summary>
/// Specify callout key GUID when using a callout.
/// </summary>
public Guid CalloutKey { get; set; }
/// <summary>
/// Specify provider key GUID.
/// </summary>
public Guid ProviderKey { get; set; }
#endregion
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
public FirewallFilterBuilder()
{
Name = string.Empty;
Description = string.Empty;
Weight = FirewallValue.Empty;
}
#endregion
#region Internal Members
internal FWPM_FILTER0 ToStruct(DisposableList list)
{
FWPM_FILTER0 ret = new FWPM_FILTER0();
ret.filterKey = FilterKey;
ret.layerKey = LayerKey;
ret.subLayerKey = SubLayerKey;
ret.displayData.name = Name;
ret.displayData.description = Description;
ret.flags = Flags;
ret.weight = Weight.ToStruct(list);
ret.action.type = ActionType;
if (ActionType.HasFlag(FirewallActionType.Callout))
{
ret.action.action.calloutKey = CalloutKey;
}
else
{
ret.action.action.filterType = FilterType;
}
if (ProviderKey != Guid.Empty)
{
ret.providerKey = list.AddStructureRef(ProviderKey).DangerousGetHandle();
}
if (Conditions.Count > 0)
{
ret.numFilterConditions = Conditions.Count;
ret.filterCondition = list.AddList(Conditions.Select(c => c.ToStruct(list))).DangerousGetHandle();
}
return ret;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiDAL.DataAccess;
using WebApiDAL.Entity;
using WebApiDAL.Model;
using WebApiDAL.ServiceManager;
namespace WebApi.Controllers
{
public class JobController : ApiController
{
private IJob jb;
private string Ermsg = "";
public JobController()
{
jb = new JobRepository();
}
[Authorize(Roles = "employer")]
[HttpPost]
[Route("api/Job/Add")]
public IHttpActionResult AddJob(Tbl_Job job)
{
var flag = jb.PostJob(job, out Ermsg);
if (flag)
{
return Json(new { success = true, responseText = "Job added succesfully", responseCode = HttpStatusCode.Created });
}
else
{
return Json(new { success = flag, responseText = Ermsg, responseCode = HttpStatusCode.InternalServerError });
}
}
[Authorize(Roles = "employer")]
[HttpPost]
[Route("api/Job/Delete")]
public IHttpActionResult DeleteJob(int JbID)
{
Tbl_JobActivity jobactivity = new Tbl_JobActivity();
var flag = jb.DeleteJob(JbID, jobactivity, out Ermsg);
if (flag)
{
return Json(new { success = true, responseText = "Job deleted succesfully", responseCode = HttpStatusCode.Created });
}
else
{
return Json(new { success = flag, responseText = Ermsg, responseCode = HttpStatusCode.InternalServerError });
}
}
[Authorize(Roles = "employer")]
[HttpPost]
[Route("api/Job/Edit")]
public IHttpActionResult UpdateJob(Tbl_Job job)
{
Tbl_JobActivity jobactivity = new Tbl_JobActivity();
var flag = jb.UpdateJob(job, jobactivity, out Ermsg);
if (flag)
{
return Json(new { success = true, responseText = "Job updated succesfully", responseCode = HttpStatusCode.Created });
}
else
{
return Json(new { success = flag, responseText = Ermsg, responseCode = HttpStatusCode.InternalServerError });
}
}
[Authorize(Roles = "seeker")]
[HttpPost]
[Route("api/Job/Apply")]
public IHttpActionResult ApplyJob(Tbl_UserJob jobapply)
{
var flag = jb.ApplyJob(jobapply, out Ermsg);
if (flag)
{
return Json(new { success = true, responseText = "Job applied succesfully", responseCode = HttpStatusCode.Created });
}
else
{
return Json(new { success = flag, responseText = Ermsg, responseCode = HttpStatusCode.InternalServerError });
}
}
[AllowAnonymous]
[Route("api/Job/AllJobs")]
public IHttpActionResult GetJobs()
{
//List<Tbl_Job> allActiveJobs = jb.GetAllActiveJobs().ToList();
var data = jb.GetAllActiveJobs().Select(p => new
{
id=p.ID,
UserID = p.UserID
,JobTypeID=p.JobTypeID
,CreatedDate=p.CreatedDate
,JobDescription=p.JobDescription
,JobLocation=p.JobLocation
,MinExperienceRequired=p.MinExperienceRequired
,MaxExperienceRequired=p.MaxExperienceRequired
,ExpireDate=p.ExpireDate
,IsActive=p.IsActive
});
return Json(new { success = true, responseText = data, responseCode = HttpStatusCode.OK });
//return Json(allActiveJobs);
}
[AllowAnonymous]
[Route("api/Job/Job")]
public IHttpActionResult GetJob(int id)
{
//List<Tbl_Job> allActiveJobs = jb.GetAllActiveJobs().ToList();
var data = jb.GetAllActiveJobs().Where(j => j.ID == id).Select(p => new
{
id = p.ID,
UserID = p.UserID,
JobTypeID = p.JobTypeID,
CreatedDate = p.CreatedDate,
JobDescription = p.JobDescription,
JobLocation = p.JobLocation,
MinExperienceRequired = p.MinExperienceRequired,
MaxExperienceRequired = p.MaxExperienceRequired,
ExpireDate = p.ExpireDate,
IsActive = p.IsActive
}).FirstOrDefault();
return Json(new { success = true, responseText = data, responseCode = HttpStatusCode.OK });
//return Json(allActiveJobs);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameBootstrap : MonoBehaviour
{
private void Start()
{
string strObj = "bootstrap";
GameObject obj = AssetBundleManager.InstantiateGameObject("bootstrap/bootstrap.u3d", strObj);
obj.name = "bootstrap";
RectTransform objTrans = obj.AddMissingComponent<RectTransform>();
objTrans.SetParent(this.transform, false);
objTrans.offsetMax = Vector2.zero;
objTrans.offsetMin = Vector2.zero;
objTrans.anchorMin = Vector2.zero;
objTrans.anchorMax = Vector2.one;
GameUtil.SetLayer(objTrans, 5);
}
}
|
/*
* Copyright 2014 Technische Universität Darmstadt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using JetBrains.Application;
using KaVE.Commons.Model.Events;
using KaVE.Commons.Model.Events.CompletionEvents;
using KaVE.Commons.Model.Events.TestRunEvents;
using KaVE.Commons.Model.Events.VisualStudio;
using KaVE.Commons.Utils.Json;
using KaVE.RS.Commons.Settings;
using KaVE.VS.FeedbackGenerator.SessionManager.Anonymize.CompletionEvents;
using KaVE.VS.FeedbackGenerator.Settings;
namespace KaVE.VS.FeedbackGenerator.SessionManager.Anonymize
{
public interface IDataExportAnonymizer
{
IDEEvent Anonymize(IDEEvent ideEvent);
}
[ShellComponent]
public class DataExportAnonymizer : IDataExportAnonymizer
{
private static readonly IDictionary<Type, IDEEventAnonymizer> Anonymizer = new Dictionary
<Type, IDEEventAnonymizer>
{
{typeof (BuildEvent), new BuildEventAnonymizer()},
{typeof (SolutionEvent), new SolutionEventAnonymizer()},
{typeof (DocumentEvent), new DocumentEventAnonymizer()},
{typeof (WindowEvent), new WindowEventAnonymizer()},
{typeof (ErrorEvent), new ErrorEventAnonymizer()},
{typeof (InfoEvent), new InfoEventAnonymizer()},
{typeof (IDEStateEvent), new IDEStateEventAnonymizer()},
{typeof (CompletionEvent), new CompletionEventAnonymizer()},
{typeof (TestRunEvent), new TestRunEventAnonymizer()}
};
private readonly ISettingsStore _settingsStore;
public DataExportAnonymizer(ISettingsStore settingsStore)
{
_settingsStore = settingsStore;
}
public IDEEvent Anonymize(IDEEvent ideEvent)
{
var clone = ideEvent.ToCompactJson().ParseJsonTo<IDEEvent>();
var settings = _settingsStore.GetSettings<AnonymizationSettings>();
var anonymizer = GetAnonymizerFor(ideEvent.GetType());
if (settings.RemoveStartTimes)
{
anonymizer.AnonymizeStartTimes(clone);
}
if (settings.RemoveDurations)
{
anonymizer.AnonymizeDurations(clone);
}
if (settings.RemoveCodeNames)
{
anonymizer.AnonymizeCodeNames(clone);
}
return clone;
}
private static IDEEventAnonymizer GetAnonymizerFor(Type eventType)
{
return Anonymizer.ContainsKey(eventType) ? Anonymizer[eventType] : new IDEEventAnonymizer();
}
}
} |
using Hayalpc.Fatura.Common.Enums;
using Hayalpc.Fatura.Data;
using Hayalpc.Fatura.Data.Models;
using Hayalpc.Fatura.Panel.Internal.Services.Interfaces;
using Hayalpc.Library.Common.Enums;
using Hayalpc.Library.Common.Helpers;
using Hayalpc.Library.Common.Results;
using Hayalpc.Library.Log;
using Hayalpc.Library.Repository.Interfaces;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using System;
using System.Linq;
namespace Hayalpc.Fatura.Panel.Internal.Services
{
public class TableHistoryService : BaseService<TableHistory>, ITableHistoryService
{
private readonly ITableDefinitionService tableDefinitionService;
private readonly IUserBulletinService userBulletinService;
private readonly IUserRoleService userRoleService;
public TableHistoryService(IRepository<TableHistory> repository, IHpLogger logger, IHpUnitOfWork<HpDbContext> unitOfWork, IMemoryCache memoryCache, ITableDefinitionService tableDefinitionService, IUserBulletinService userBulletinService, IUserRoleService userRoleService)
: base(repository, logger, unitOfWork, memoryCache)
{
this.tableDefinitionService = tableDefinitionService;
this.userBulletinService = userBulletinService;
this.userRoleService = userRoleService;
}
public override IDataResult<TableHistory> Add(TableHistory model) => throw new NotImplementedException();
public Result Approve(long Id)
{
Result approveResponse = null;
var modelRes = Get(Id);
if (modelRes.IsSuccess)
{
var model = modelRes.Data;
if (model.CreateUserId != RequestHelper.UserId)
{
var tableDefinition = tableDefinitionService.Get(model.TableDefinitionId).Data;
if (model.Status == TableHistoryStatus.New && RequestHelper.User.UserRoles.Where(x => x.RoleId == model.RoleId1).Any())
{
model.Status = tableDefinition.RoleId2 > 0 ? TableHistoryStatus.Step1 : TableHistoryStatus.Approved;
if(tableDefinition.RoleId2 > 0)
{
var str = "Onayınızı bekleyen talep bulunmaktadır.";
var userBulletin = userRoleService.GetByRoleId(tableDefinition.RoleId2 ?? 0).Select(x => new UserBulletin {
DealerId = 0,
RoleGroupId = tableDefinition.RoleId2 ?? 0,
UserId = 0,
ActionType = "approveRequest",
Title = "Talep Onay",
Message = str,
Type = UserBulletinType.Warning,
Status = UserBulletinStatus.Unread,
StartDate = DateTime.Now,
ExpireDate = DateTime.Now.AddDays(3),
CreateTime = DateTime.Now,
CreateUserId = -1,
}).ToList();
userBulletinService.AddRange(userBulletin);
}
}
else if (model.UpdateUserId == RequestHelper.UserId)
{
return new ErrorResult("FirstApproverCannotSecondApprove");
}
else if (model.Status == TableHistoryStatus.Step1 && RequestHelper.User.UserRoles.Where(x => x.RoleId == model.RoleId2).Any())
{
model.Status = TableHistoryStatus.Approved;
}
else
{
return new ErrorResult("InvalidApprove");
}
var fullAssembly = tableDefinition.Namespace + "." + tableDefinition.ModelName + ", " + tableDefinition.Assembly;
Type modelType = Type.GetType(fullAssembly);
if (modelType != null)
{
var result = Update(model, "Status");
if (result.Success)
{
if (model.Status == TableHistoryStatus.Approved)
{
try
{
IDataResult<IHpModel> modelCusRes = null;
if (tableDefinition.ActionType == ActionType.Insert)
{
var insertData = (IHpModel)JsonConvert.DeserializeObject(model.NewData, modelType);
modelCusRes = base.AddCustom(insertData);
}
else if (tableDefinition.ActionType == ActionType.Update)
{
var updateData = (IHpModel)JsonConvert.DeserializeObject(model.NewData, modelType);
modelCusRes = base.UpdateCustom(updateData);
}
else if (tableDefinition.ActionType == ActionType.Delete)
{
}
else if (tableDefinition.ActionType == ActionType.Approve)
{
}
else
approveResponse = new ErrorResult("InvalidActionType");
if (modelCusRes != null && modelCusRes.IsSuccess)
{
approveResponse = new SuccessResult("ApproveSuccess");
model.DataId = modelCusRes.Data.Id;
Update(model, "DataId");
}
else
{
logger.Error(modelCusRes);
approveResponse = new ErrorResult("CouldNotApprove");
}
}
catch (Exception exp)
{
logger.Error(exp.ToString());
approveResponse = new ErrorResult("InternalError");
}
}
else
approveResponse = new SuccessResult("WaitingNextApprove");
}
else
{
logger.Error(result);
approveResponse = new ErrorResult("InternalError");
}
}
else
approveResponse = new ErrorResult("InvalidModel");
}
else
approveResponse = new ErrorResult("CreatedUserCannotApprove");
}
else
approveResponse = new ErrorResult("NotFound");
return approveResponse;
}
public Result Reject(long Id)
{
var modelRes = Get(Id);
if (modelRes.IsSuccess)
{
var model = modelRes.Data;
var tableDefinition = tableDefinitionService.Get(model.TableDefinitionId).Data;
if (model.CreateUserId == RequestHelper.UserId || RequestHelper.User.UserRoles.Where(x => x.RoleId == model.RoleId1 || x.RoleId == model.RoleId2).Any())
{
model.Status = TableHistoryStatus.Rejected;
Update(model, "Status");
return new SuccessResult("RejectSuccess");
}
else
{
return new ErrorResult("InvalidPermission");
}
}
else
{
return new ErrorResult("NotFound");
}
}
public override IQueryable<TableHistory> BeforeSearch(IQueryable<TableHistory> req)
{
if (Fatura.Common.Helpers.RequestHelper.DealerId > 0)
{
req = req.Where(x => x.DealerId == Fatura.Common.Helpers.RequestHelper.DealerId);
}
return base.BeforeSearch(req);
}
}
}
|
using Domain;
namespace App
{
public interface IStudentEditionRepository
{
Student Get(string registration);
void Update(Student student);
}
} |
using System;
using System.Collections.Generic;
using ETravel.Coffee.DataAccess.Entities;
namespace ETravel.Coffee.DataAccess.Interfaces
{
public interface IOrderItemsRepository
{
IList<OrderItem> ForOrderId(Guid orderId);
OrderItem GetById(Guid id);
void Save(OrderItem item);
void Update(OrderItem item);
void Delete(Guid id);
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class Block : MonoBehaviour {
public uint layer = 0;
public bool hasCollider = true;
public float mass = 80;
public bool isLarge = true;
public Vector2I size = Vector2I.ONE;
public Vector2I SmallSize
{
get {
return isLarge ? size * Grid.BLOCKS_PER_LARGE_BLOCK : size;
}
}
[HideInInspector]
public Vector2I blockPos;
protected ShipManager ship;
/// <summary>
/// Given a block position relative to prefab block origin point, return a vec relative to placed block.
/// </summary>
/// <param name="amount"></param>
/// <returns></returns>
public Vector2I RotateBlock(Vector2I blockPos) {
Vector2I result = new Vector2I(blockPos);
switch(rotation) {
case 0:
return result;
case 1:
int t = result.x;
result.x = result.y;
result.y = -t + PlacedSize(rotation).y;
return result;
case 2:
result.x = -result.x + PlacedSize(rotation).x;
result.y = -result.y + PlacedSize(rotation).y;
return result;
case 3:
int t2 = result.x;
result.x = -result.y + PlacedSize(rotation).x;
result.y = t2;
return result;
}
throw new Exception("Unhandled rotation");
}
/// <summary>
/// Given a block position relative to prefab block origin point, return a vec relative to placed block.
/// </summary>
/// <param name="amount"></param>
/// <returns></returns>
public Vector2I RotateBlockSmall(Vector2I blockPos) {
Vector2I result = new Vector2I(blockPos);
switch(rotation) {
case 0:
return result;
case 1:
int t = result.x;
result.x = result.y;
result.y = -t + PlacedSizeSmall(rotation).y;
return result;
case 2:
result.x = -result.x + PlacedSizeSmall(rotation).x;
result.y = -result.y + PlacedSizeSmall(rotation).y;
return result;
case 3:
int t2 = result.x;
result.x = -result.y + PlacedSizeSmall(rotation).x;
result.y = t2;
return result;
}
throw new Exception("Unhandled rotation");
}
/// <summary>
/// Given a vec relative to prefab, return a vec relative to placed block in game units.
/// This only works for children game objects after the block has been placed in the world, it rotates around the sprite center point, not block placement position
/// </summary>
/// <param name="amount"></param>
/// <returns></returns>
public Vector2 RotateBlockSmall(Vector2 result) {
switch(rotation) {
case 0:
return result;
case 1:
float t = result.x;
result.x = result.y;
result.y = -t;
return result;
case 2:
result.x = -result.x;
result.y = -result.y;
return result;
case 3:
float t2 = result.x;
result.x = -result.y;
result.y = t2;
return result;
}
throw new Exception("Unhandled rotation");
}
public Vector2I PlacedSize(int rotation) {
Vector2I placedSize = size.Rotated(rotation);
placedSize.x = Mathf.Abs(placedSize.x);
placedSize.y = Mathf.Abs(placedSize.y);
return placedSize;
}
public Vector2I PlacedSizeSmall(int rotation) {
return isLarge ? this.PlacedSize(rotation) * Grid.BLOCKS_PER_LARGE_BLOCK : this.PlacedSize(rotation);
}
public Vector2 CenterOffset(int rotation) {
return PlacedSizeSmall(rotation) * 0.5f * Grid.UNITS_PER_BLOCK;
}
public Sprite[] spritesRotated;
[HideInInspector]
public byte rotation = 0;
public Item createsItem;
public void Init(byte rotation) {
this.rotation = rotation;
}
public bool CanBePlacedIn(List<Block> column) {
foreach(Block existing in column) {
if(existing.layer == this.layer)
return false;
}
if(this.layer == 10) {
return column.Exists(existing => {
return existing.layer == 0;
});
} else {
return true;
}
}
public bool CanBeAttached(int direction, Block other) {
return other.layer >= layer;
}
// Use this for initialization
void Start() {
Debug.Assert(spritesRotated.Length > 0, "Missing sprites");
SpriteRenderer sr = GetComponent<SpriteRenderer>();
sr.sortingOrder = (int)layer;
sr.sprite = GetSpriteForRotation(rotation);
if(hasCollider) {
BoxCollider2D collider = gameObject.AddComponent<BoxCollider2D>();
}
}
public Sprite GetSpriteForRotation(byte rotation) {
return spritesRotated[rotation % spritesRotated.Length];
}
public virtual void OnPlace(ShipManager ship, Vector2I blockPos) {
this.blockPos = blockPos;
this.ship = ship;
// TODO: Integrate better into block
PipeConnections c = GetComponent<PipeConnections>();
if(c != null) {
c.OnPlace();
}
// TODO: Move rotating objects to known child
int children = transform.childCount;
for(int i = 0; i < children; i++) {
Vector2 rotated = RotateBlockSmall(transform.GetChild(i).localPosition);
transform.GetChild(i).localPosition = new Vector3(rotated.x, rotated.y, transform.GetChild(i).localPosition.z);
transform.GetChild(i).localRotation = Quaternion.Euler((rotation +1) * 90, 90, 0);
}
}
public virtual void OnRemove(ShipManager ship, Vector2I blockPos) {
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cadastro.API.Data;
using Cadastro.API.Interface;
using Cadastro.API.Model;
using Microsoft.AspNet.OData.Extensions;
using Microsoft.AspNet.OData.Query;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Cadastro.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddMvc();
services.AddODataQueryFilter();
services.AddOData();
services.Configure<Settings>(options =>
{
options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
options.Database = Configuration.GetSection("MongoConnection:Database").Value;
});
services.AddTransient<IProdutoRepository, ProdutoRepository>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("CorsPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc(routeBuilder =>
{
routeBuilder
.Select()
.Expand()
.Filter()
.OrderBy(QueryOptionSetting.Allowed)
.MaxTop(2000)
.Count();
routeBuilder.EnableDependencyInjection();
});
}
}
}
|
using Entities.Concrete;
using FluentValidation;
namespace Business.ValidationRules.FluentValidation
{
public class CustomerCreditCardValidator:AbstractValidator<CustomerCreditCard>
{
public CustomerCreditCardValidator()
{
RuleFor(c => c.CardId).NotEmpty();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Xml;
using Microsoft.Xna.Framework;
using MonoGame.Extended.Gui.Controls;
namespace MonoGame.Extended.Gui.Markup
{
public class MarkupParser
{
public MarkupParser()
{
}
private static readonly Dictionary<string, Type> _controlTypes =
typeof(Control).Assembly
.ExportedTypes
.Where(t => t.IsSubclassOf(typeof(Control)))
.ToDictionary(t => t.Name, StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<Type, Func<string, object>> _converters =
new Dictionary<Type, Func<string, object>>
{
{typeof(object), s => s},
{typeof(string), s => s},
{typeof(bool), s => bool.Parse(s)},
{typeof(int), s => int.Parse(s)},
{typeof(Color), s => s.StartsWith("#") ? ColorHelper.FromHex(s) : ColorHelper.FromName(s)}
};
private static object ConvertValue(Type propertyType, string input, object dataContext)
{
var value = ParseBinding(input, dataContext);
if (_converters.TryGetValue(propertyType, out var converter))
return converter(value); //property.SetValue(control, converter(value));
if (propertyType.IsEnum)
return
Enum.Parse(propertyType, value,
true); // property.SetValue(control, Enum.Parse(propertyType, value, true));
throw new InvalidOperationException($"Converter not found for {propertyType}");
}
private static object ParseChildNode(XmlNode node, Control parent, object dataContext)
{
if (node is XmlText)
return node.InnerText.Trim();
if (_controlTypes.TryGetValue(node.Name, out var type))
{
var typeInfo = type.GetTypeInfo();
var control = (Control) Activator.CreateInstance(type);
// ReSharper disable once AssignNullToNotNullAttribute
foreach (var attribute in node.Attributes.Cast<XmlAttribute>())
{
var property = typeInfo.GetProperty(attribute.Name);
if (property != null)
{
var value = ConvertValue(property.PropertyType, attribute.Value, dataContext);
property.SetValue(control, value);
}
else
{
var parts = attribute.Name.Split('.');
var parentType = parts[0];
var propertyName = parts[1];
var propertyType = parent.GetAttachedPropertyType(propertyName);
var propertyValue = ConvertValue(propertyType, attribute.Value, dataContext);
if (!string.Equals(parent.GetType().Name, parentType, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(
$"Attached properties are only supported on the immediate parent type {parentType}");
control.SetAttachedProperty(propertyName, propertyValue);
}
}
if (node.HasChildNodes)
{
switch (control)
{
case ContentControl contentControl:
if (node.ChildNodes.Count > 1)
throw new InvalidOperationException("A content control can only have one child");
contentControl.Content = ParseChildNode(node.ChildNodes[0], control, dataContext);
break;
case LayoutControl layoutControl:
foreach (var childControl in ParseChildNodes(node.ChildNodes, control, dataContext))
layoutControl.Items.Add(childControl as Control);
break;
}
}
return control;
}
throw new InvalidOperationException($"Unknown control type {node.Name}");
}
private static string ParseBinding(string expression, object dataContext)
{
if (dataContext != null && expression.StartsWith("{{") && expression.EndsWith("}}"))
{
var binding = expression.Substring(2, expression.Length - 4);
var bindingValue = dataContext
.GetType()
.GetProperty(binding)
?.GetValue(dataContext);
return $"{bindingValue}";
}
return expression;
}
private static IEnumerable<object> ParseChildNodes(XmlNodeList nodes, Control parent, object dataContext)
{
foreach (var node in nodes.Cast<XmlNode>())
{
if (node.Name == "xml")
{
// TODO: Validate header
}
else
{
yield return ParseChildNode(node, parent, dataContext);
}
}
}
public Control Parse(string filePath, object dataContext)
{
var d = new XmlDocument();
d.Load(filePath);
return ParseChildNodes(d.ChildNodes, null, dataContext)
.LastOrDefault() as Control;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace RecuperacionParcial
{
class Linea3D : LineaAbstracta<Punto3D>
{
public override Punto3D[] Punto => throw new NotImplementedException();
public override double Distancia(Punto3D puntoA, Punto3D puntoB)
{
double x = Math.Pow(puntoA.X - puntoB.X, 2);
double y = Math.Pow(puntoA.Y - puntoB.Y, 2);
double z = Math.Pow(puntoA.Z - puntoB.Z, 2);
return Math.Sqrt(x + y + z);
throw new NotImplementedException();
}
public Linea3D(Punto3D[] puntos)
{
Punto = puntos;
}
}
}
|
using System.Reactive;
using System.Reactive.Linq;
using MVVMSidekick.ViewModels;
using MVVMSidekick.Views;
using MVVMSidekick.Reactive;
using MVVMSidekick.Services;
using MVVMSidekick.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using IndoorMap.Models;
using Newtonsoft.Json;
using Windows.UI.Xaml.Controls;
using Windows.UI.Popups;
using IndoorMap.Controller;
using Windows.Phone.UI.Input;
using IndoorMap.Helpers;
using Windows.UI.Core;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
namespace IndoorMap.ViewModels
{
[DataContract]
public class AtlasPage_Model : ViewModelBase<AtlasPage_Model>
{
// If you have install the code sniplets, use "propvm + [tab] +[tab]" create a property。
// 如果您已经安装了 MVVMSidekick 代码片段,请用 propvm +tab +tab 输入属性
public WebView webView;
public Building Building;
public AtlasPage_Model()
{
if (IsInDesignMode)
{
SelectedMallModel = new MallModel()
{
addr = "某某区 某某路 ",
desc = "描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述描述",
name = "某某某商场",
opentime = "20:00 ------ 10:00",
traffic = "公交路线"
};
}
}
public AtlasPage_Model(MallModel mall)
{
//[{"Floor1": "541797c6ac4711c3332d6cd1",
//"Floor2": "541797c6ac4711c3332d6cs1"}]
SelectedMallModel = mall;
Building = mall.buildings.FirstOrDefault();
//Title = Building.name;
}
//SelectedMallModel
public MallModel SelectedMallModel
{
get { return _SelectedMallModelLocator(this).Value; }
set { _SelectedMallModelLocator(this).SetValueAndTryNotify(value); }
}
#region Property MallModel SelectedMallModel Setup
protected Property<MallModel> _SelectedMallModel = new Property<MallModel> { LocatorFunc = _SelectedMallModelLocator };
static Func<BindableBase, ValueContainer<MallModel>> _SelectedMallModelLocator = RegisterContainerLocator<MallModel>("SelectedMallModel", model => model.Initialize("SelectedMallModel", ref model._SelectedMallModel, ref _SelectedMallModelLocator, _SelectedMallModelDefaultValueFactory));
static Func<BindableBase, MallModel> _SelectedMallModelDefaultValueFactory = m => new MallModel();
#endregion
//AutoSuggestText
public String AutoSuggestText
{
get { return _AutoSuggestTextLocator(this).Value; }
set { _AutoSuggestTextLocator(this).SetValueAndTryNotify(value); }
}
#region Property String AutoSuggestText Setup
protected Property<String> _AutoSuggestText = new Property<String> { LocatorFunc = _AutoSuggestTextLocator };
static Func<BindableBase, ValueContainer<String>> _AutoSuggestTextLocator = RegisterContainerLocator<String>("AutoSuggestText", model => model.Initialize("AutoSuggestText", ref model._AutoSuggestText, ref _AutoSuggestTextLocator, _AutoSuggestTextDefaultValueFactory));
static Func<BindableBase, String> _AutoSuggestTextDefaultValueFactory = m => string.Empty;
#endregion
public String Title
{
get { return _TitleLocator(this).Value; }
set { _TitleLocator(this).SetValueAndTryNotify(value); }
}
#region Property String Title Setup
protected Property<String> _Title = new Property<String> { LocatorFunc = _TitleLocator };
static Func<BindableBase, ValueContainer<String>> _TitleLocator = RegisterContainerLocator<String>("Title", model => model.Initialize("Title", ref model._Title, ref _TitleLocator, _TitleDefaultValueFactory));
static Func<BindableBase, String> _TitleDefaultValueFactory = m => m.GetType().Name;
#endregion
//ShopSearchList
public List<ShopSearchResultModel> ShopSearchList
{
get { return _ShopSearchListLocator(this).Value; }
set { _ShopSearchListLocator(this).SetValueAndTryNotify(value); }
}
#region Property List<ShopSearchResultModel> ShopSearchList Setup
protected Property<List<ShopSearchResultModel>> _ShopSearchList = new Property<List<ShopSearchResultModel>> { LocatorFunc = _ShopSearchListLocator };
static Func<BindableBase, ValueContainer<List<ShopSearchResultModel>>> _ShopSearchListLocator = RegisterContainerLocator<List<ShopSearchResultModel>>("ShopSearchList", model => model.Initialize("ShopSearchList", ref model._ShopSearchList, ref _ShopSearchListLocator, _ShopSearchListDefaultValueFactory));
static Func<BindableBase, List<ShopSearchResultModel>> _ShopSearchListDefaultValueFactory = m => new List<ShopSearchResultModel>();
#endregion
#region Life Time Event Handling
///// <summary>
///// This will be invoked by view when this viewmodel instance is set to view's ViewModel property.
///// </summary>
///// <param name="view">Set target</param>
///// <param name="oldValue">Value before set.</param>
///// <returns>Task awaiter</returns>
//protected override Task OnBindedToView(MVVMSidekick.Views.IView view, IViewModel oldValue)
//{
// return base.OnBindedToView(view, oldValue);
//}
///// <summary>
///// This will be invoked by view when this instance of viewmodel in ViewModel property is overwritten.
///// </summary>
///// <param name="view">Overwrite target view.</param>
///// <param name="newValue">The value replacing </param>
///// <returns>Task awaiter</returns>
//protected override Task OnUnbindedFromView(MVVMSidekick.Views.IView view, IViewModel newValue)
//{
// return base.OnUnbindedFromView(view, newValue);
//}
///// <summary>
///// This will be invoked by view when the view fires Load event and this viewmodel instance is already in view's ViewModel property
///// </summary>
///// <param name="view">View that firing Load event</param>
///// <returns>Task awaiter</returns>
//protected override Task OnBindedViewLoad(MVVMSidekick.Views.IView view)
//{
// return base.OnBindedViewLoad(view);
//}
///// <summary>
///// This will be invoked by view when the view fires Unload event and this viewmodel instance is still in view's ViewModel property
///// </summary>
///// <param name="view">View that firing Unload event</param>
///// <returns>Task awaiter</returns>
//protected override Task OnBindedViewUnload(MVVMSidekick.Views.IView view)
//{
// return base.OnBindedViewUnload(view);
//}
///// <summary>
///// <para>If dispose actions got exceptions, will handled here. </para>
///// </summary>
///// <param name="exceptions">
///// <para>The exception and dispose infomation</para>
///// </param>
//protected override async void OnDisposeExceptions(IList<DisposeInfo> exceptions)
//{
// base.OnDisposeExceptions(exceptions);
// await TaskExHelper.Yield();
//}
#endregion
#region --------------------- Command -------------------------
//Loading Map when the webview is loaded.
public CommandModel<ReactiveCommand, String> CommandAtlasLoading
{
get { return _CommandAtlasLoadingLocator(this).Value; }
set { _CommandAtlasLoadingLocator(this).SetValueAndTryNotify(value); }
}
#region Property CommandModel<ReactiveCommand, String> CommandAtlasLoading Setup
protected Property<CommandModel<ReactiveCommand, String>> _CommandAtlasLoading = new Property<CommandModel<ReactiveCommand, String>> { LocatorFunc = _CommandAtlasLoadingLocator };
static Func<BindableBase, ValueContainer<CommandModel<ReactiveCommand, String>>> _CommandAtlasLoadingLocator = RegisterContainerLocator<CommandModel<ReactiveCommand, String>>("CommandAtlasLoading", model => model.Initialize("CommandAtlasLoading", ref model._CommandAtlasLoading, ref _CommandAtlasLoadingLocator, _CommandAtlasLoadingDefaultValueFactory));
static Func<BindableBase, CommandModel<ReactiveCommand, String>> _CommandAtlasLoadingDefaultValueFactory =
model =>
{
var resource = "AtlasLoading"; // Command resource
var commandId = "AtlasLoading";
var vm = CastToCurrentType(model);
var cmd = new ReactiveCommand(canExecute: true) { ViewModel = model }; //New Command Core
cmd.DoExecuteUIBusyTask(
vm,
async e =>
{
//await vm.StageManager.DefaultStage.Show(new DetailPage_Model());
//Todo: Add NavigateToAbout logic here, or
await MVVMSidekick.Utilities.TaskExHelper.Yield();
vm.webView = e.EventArgs.Parameter as WebView;
string param = vm.GetInvokeParamsInJson();
double altlasWith = 0;
double width = ApplicationView.GetForCurrentView().VisibleBounds.Width;
//手机 并且是 横屏
if ((DisplayInformation.GetForCurrentView().CurrentOrientation == DisplayOrientations.LandscapeFlipped ||
DisplayInformation.GetForCurrentView().CurrentOrientation == DisplayOrientations.Landscape)
&& Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile")
{
altlasWith = width * 3 / 5 - 30;
}
else
{
altlasWith = (width <= 500) ? width : 700;
}
await vm.webView.InvokeScriptAsync("StartInit", new string[] { param, altlasWith.ToString() });
// altlasWith.ToString() });
})
.DoNotifyDefaultEventRouter(vm, commandId)
.Subscribe()
.DisposeWith(vm);
var cmdmdl = cmd.CreateCommandModel(resource);
cmdmdl.ListenToIsUIBusy(model: vm, canExecuteWhenBusy: false);
return cmdmdl;
};
#endregion
//when the webview's event: scriptNotify is invoke
//CommandLvMallItemClick
public CommandModel<ReactiveCommand, String> CommandScriptNotify
{
get { return _CommandScriptNotifyLocator(this).Value; }
set { _CommandScriptNotifyLocator(this).SetValueAndTryNotify(value); }
}
#region Property CommandModel<ReactiveCommand, String> CommandScriptNotify Setup
protected Property<CommandModel<ReactiveCommand, String>> _CommandScriptNotify = new Property<CommandModel<ReactiveCommand, String>> { LocatorFunc = _CommandScriptNotifyLocator };
static Func<BindableBase, ValueContainer<CommandModel<ReactiveCommand, String>>> _CommandScriptNotifyLocator = RegisterContainerLocator<CommandModel<ReactiveCommand, String>>("CommandScriptNotify", model => model.Initialize("CommandScriptNotify", ref model._CommandScriptNotify, ref _CommandScriptNotifyLocator, _CommandScriptNotifyDefaultValueFactory));
static Func<BindableBase, CommandModel<ReactiveCommand, String>> _CommandScriptNotifyDefaultValueFactory =
model =>
{
var resource = "ScriptNotify"; // Command resource
var commandId = "ScriptNotify";
var vm = CastToCurrentType(model);
var cmd = new ReactiveCommand(canExecute: true) { ViewModel = model }; //New Command Core
cmd.DoExecuteUIBusyTask(
vm,
async e =>
{
//await vm.StageManager.DefaultStage.Show(new DetailPage_Model());
//Todo: Add NavigateToAbout logic here, or
await MVVMSidekick.Utilities.TaskExHelper.Yield();
//await vm.StageManager.DefaultStage.Show(new DetailPage_Model());
//Todo: Add NavigateToAbout logic here, or
NotifyEventArgs notify = e.EventArgs.Parameter as NotifyEventArgs;
var split = notify.Value.Split('&');
//split[0]: POI ID ; split[1]: POI Name
if (split[0].Length == 1)
{
await new MessageDialog("这是:" + split[1]).ShowAsync();
}
else
{
//await new MessageDialog("接口中未提供店铺有用信息,后续版本将添加").ShowAsync();
//GoToDetailsPage
//string url = string.Format("http://op.juhe.cn/atlasyun/shop/detail?key={0}&cityid={1}&shopid={2}",
// Configmanager.INDOORMAP_APPKEY, AppSettings.Intance.SelectedCityId, split[0]);
// await vm.StageManager.DefaultStage.Show(new ShopDetailsPage_Model(url));
}
}
)
.DoNotifyDefaultEventRouter(vm, commandId)
.Subscribe()
.DisposeWith(vm);
var cmdmdl = cmd.CreateCommandModel(resource);
cmdmdl.ListenToIsUIBusy(model: vm, canExecuteWhenBusy: false);
return cmdmdl;
};
#endregion
//CommandAutoSuggestionQuerySubmitted
public CommandModel<ReactiveCommand, String> CommandAutoSuggestionQuerySubmitted
{
get { return _CommandAutoSuggestionQuerySubmittedLocator(this).Value; }
set { _CommandAutoSuggestionQuerySubmittedLocator(this).SetValueAndTryNotify(value); }
}
#region Property CommandModel<ReactiveCommand, String> CommandAutoSuggestionQuerySubmitted Setup
protected Property<CommandModel<ReactiveCommand, String>> _CommandAutoSuggestionQuerySubmitted = new Property<CommandModel<ReactiveCommand, String>> { LocatorFunc = _CommandAutoSuggestionQuerySubmittedLocator };
static Func<BindableBase, ValueContainer<CommandModel<ReactiveCommand, String>>> _CommandAutoSuggestionQuerySubmittedLocator = RegisterContainerLocator<CommandModel<ReactiveCommand, String>>("CommandAutoSuggestionQuerySubmitted", model => model.Initialize("CommandAutoSuggestionQuerySubmitted", ref model._CommandAutoSuggestionQuerySubmitted, ref _CommandAutoSuggestionQuerySubmittedLocator, _CommandAutoSuggestionQuerySubmittedDefaultValueFactory));
static Func<BindableBase, CommandModel<ReactiveCommand, String>> _CommandAutoSuggestionQuerySubmittedDefaultValueFactory =
model =>
{
var resource = "AutoSuggestionQuerySubmitted"; // Command resource
var commandId = "AutoSuggestionQuerySubmitted";
var vm = CastToCurrentType(model);
var cmd = new ReactiveCommand(canExecute: true) { ViewModel = model }; //New Command Core
cmd.DoExecuteUIBusyTask(
vm,
async e =>
{
//await vm.StageManager.DefaultStage.Show(new DetailPage_Model());
//Todo: Add NavigateToAbout logic here, or
await MVVMSidekick.Utilities.TaskExHelper.Yield();
if (string.IsNullOrEmpty(vm.AutoSuggestText)) return;
var args = e.EventArgs.Parameter as AutoSuggestBoxQuerySubmittedEventArgs;
if (args.ChosenSuggestion != null)
{
var selectedShop = (args.ChosenSuggestion as ShopSearchResultModel);
if(selectedShop.ch_name == "未查询到结果")
{
return;
}
await vm.webView.InvokeScriptAsync("SetFloor", new string[] { selectedShop.floor.name });
await vm.webView.InvokeScriptAsync("MoveToPoiId", new string[] { selectedShop.id, "true" });
await vm.webView.InvokeScriptAsync("SetWidth", new string[] { "100" });
}
else
{
string searchUrl = string.Format(@"http://ap.atlasyun.com/poi/shop/search?kw={0}&bid={1}", vm.AutoSuggestText, vm.Building.id);
FormAction action = new FormAction(searchUrl);
action.isShowWaitingPanel = true;
action.Run();
action.FormActionCompleted += (result, tag) =>
{
vm.PraseSearchResult(result, tag);
};
}
}
)
.DoNotifyDefaultEventRouter(vm, commandId)
.Subscribe()
.DisposeWith(vm);
var cmdmdl = cmd.CreateCommandModel(resource);
cmdmdl.ListenToIsUIBusy(model: vm, canExecuteWhenBusy: false);
return cmdmdl;
};
private void PraseSearchResult(string result, string tag)
{
var shopList = JsonConvert.DeserializeObject<List<ShopSearchResultModel>>(result);
if (shopList.Any())
{
ShopSearchList = shopList;
}
else
{
//没有数据
ShopSearchList = new List<ShopSearchResultModel>() { new ShopSearchResultModel() { ch_name = "未查询到结果" } };
}
}
#endregion
#endregion
#region ----------------------- Method -------------------------
public string GetInvokeParamsInJson()
{
var floors = Building.floors;
List<Object> obj = new List<Object>() { };
foreach (var floor in floors)
{
if (!string.IsNullOrEmpty(floor.floorB3))
{
obj.Add(new FloorB3Class() { FloorB3 = floor.floorB3 });
continue;
}
if (!string.IsNullOrEmpty(floor.floorB2))
{
obj.Add(new FloorB2Class() { FloorB2 = floor.floorB2 });
continue;
}
if (!string.IsNullOrEmpty(floor.floorB1))
{
obj.Add(new FloorB1Class() { FloorB1 = floor.floorB1 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor1))
{
obj.Add(new Floor1Class() { Floor1 = floor.floor1 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor2))
{
obj.Add(new Floor2Class() { Floor2 = floor.floor2 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor3))
{
obj.Add(new Floor3Class() { Floor3 = floor.floor3 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor4))
{
obj.Add(new Floor4Class() { Floor4 = floor.floor4 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor5))
{
obj.Add(new Floor5Class() { Floor5 = floor.floor5 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor6))
{
obj.Add(new Floor6Class() { Floor6 = floor.floor6 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor7))
{
obj.Add(new Floor7Class() { Floor7 = floor.floor7 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor8))
{
obj.Add(new Floor8Class() { Floor8 = floor.floor8 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor9))
{
obj.Add(new Floor9Class() { Floor9 = floor.floor9 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor10))
{
obj.Add(new Floor10Class() { Floor10 = floor.floor10 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor11))
{
obj.Add(new Floor11Class() { Floor11 = floor.floor11 });
continue;
}
if (!string.IsNullOrEmpty(floor.floor12))
{
obj.Add(new Floor12Class() { Floor12 = floor.floor12 });
continue;
}
}
//object[] obj = new object[] {
// new FloorB2Class{ FloorB2 = "539098c7b8604a3d36934658"},
// new FloorB1Class { FloorB1 = "539098c7b8604a3d3693463d"},
// new Floor1Class { Floor1 = "539098c7b8604a3d369345ed"} };
return JsonConvert.SerializeObject(obj);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Football.Models
{
public class Team
{
public Team(string name)
{
this.Name = name;
}
private string name;
private int rating=0;
public string Name
{
get { return name; }
set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("A name should not be empty.");
}
name = value;
}
}
private List<Player> players = new List<Player>();
public int Rating
{
get { return rating; }
private set { rating = value; }
}
public void AddPlayer(Player player)
{
players.Add(player);
}
public void RemovePlayer(string playerName)
{
if (players.FirstOrDefault(x => x.Name == playerName) == null)
{
throw new InvalidOperationException(string.Format("Player {0} is not in {1} team.", playerName, this.Name));
}
else
{
players.Remove(players.First(x => x.Name == playerName));
}
}
public void CalculateRating()
{
double sum = 0;
foreach (var player in players)
{
sum += player.SkillLevel;
}
Rating = (int)Math.Round((sum / players.Count));
if (players.Count ==0)
{
Rating = 0;
}
Console.WriteLine("{0} - {1}", this.Name, Rating);
}
}
}
|
using LAP_PowerMining.Core.KrakenComponents;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LAP_PowerMining.Core.Services
{
public class KrakenService
{
public KrakenService()
{
KrakenClient.KrakenClient kClient = new KrakenClient.KrakenClient();
var tickerJson = kClient.GetTicker(new List<string> { "XXBTZEUR" });
var historyJson = kClient.GetRecentTrades("XXBTZEUR", 137589964200000000);
Ticker ticker = new Ticker(tickerJson.ToString());
}
}
} |
using AutoMapper;
using Contoso.AutoMapperProfiles;
using Contoso.XPlatform.AutoMapperProfiles;
using Contoso.XPlatform.MappingProfiles;
namespace Microsoft.Extensions.DependencyInjection
{
internal static class AutoMapperServices
{
internal static IServiceCollection AddAutoMapperServices(this IServiceCollection services)
{
return services.AddSingleton<IConfigurationProvider>
(
new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(DescriptorToOperatorMappingProfile), typeof(CommandButtonProfile), typeof(MenuItemProfile));
cfg.AllowNullCollections = true;
})
).AddTransient<IMapper>
(
sp => new Mapper
(
sp.GetRequiredService<AutoMapper.IConfigurationProvider>(),
sp.GetService
)
);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KillVolume : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.GetComponent<Character>())
{
if (other.GetComponent<Character>().team == Team.Red)
{
GameMode.m_TeamRed.Remove(other.gameObject);
}
else
{
GameMode.m_TeamBlue.Remove(other.gameObject);
}
Destroy(other.gameObject);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ControlBase : MonoBehaviour
{
public UISprite rootSprite;
public UIAtlas atlas;
private Dictionary<string, List<Object>> map = new Dictionary<string, List<Object>>();
void Start()
{
}
public void RemoveCategory(string category)
{
if (map.ContainsKey(category))
{
for (int i = 0; i < map[category].Count; i++)
{
NGUITools.DestroyImmediate(map[category][i]);
}
}
}
public UISprite AddSprite(string category, string name, float x, float y, int xSize, int ySize)
{
UISprite sprite = NGUITools.AddSprite(rootSprite.gameObject, atlas, name);
sprite.MakePixelPerfect();
sprite.transform.localPosition = new Vector3(x, y, 0);
sprite.SetDimensions(xSize, ySize);
if (map.ContainsKey(category))
{
}
else
{
map.Add(category, new List<Object>());
}
map[category].Add(sprite);
return sprite;
}
public GameObject AddWidget(string category, GameObject prefab, float x, float y)
{
return AddWidget(rootSprite.gameObject, category, prefab, x, y);
}
public GameObject AddWidget(GameObject root, string category, GameObject prefab, float x, float y)
{
GameObject res = NGUITools.AddChild(root, prefab);
res.transform.localPosition = new Vector3(x, y, 0);
if (map.ContainsKey(category))
{
}
else
{
map.Add(category, new List<Object>());
}
map[category].Add(res);
return res;
}
} |
namespace Smart.Mock.Data.SqlServer;
using Microsoft.SqlServer.TransactSql.ScriptDom;
public static class DefaultParser
{
private static Func<TSqlParser> parserFactory = () => new TSql130Parser(true);
public static void SetFactory(Func<TSqlParser> factory)
{
parserFactory = factory;
}
public static TSqlParser Create() => parserFactory();
}
|
using HAGVeT.Helper;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
namespace HAGVeT
{
/// <summary>
/// Interaktionslogik für MainPage.xaml
/// </summary>
public partial class MainPage : Page
{
/// <summary>
/// True, if the TreeViewSelectionChanged event handler should execute in documents tab.
/// </summary>
private bool enableTabDocumentsTreeViewSelectionChangedEvent = false;
/// <summary>
/// True, if the TreeViewSelectionChanged event handler should execute in pictures tab.
/// </summary>
private bool enableTabDPicturesTreeViewSelectionChangedEvent = false;
/// <summary>
/// Constructor
/// </summary>
public MainPage()
{
InitializeComponent();
setTabsEnabled(false);
}
#region Helper methods
/// <summary>
/// Creates and opens a directory.
/// </summary>
public void createDirectory()
{
var path = chooseDirectory(true);
var dirinfo = new DirectoryInfo(path);
if (dirinfo.GetFiles().Length != 0 || dirinfo.GetDirectories().Length != 0)
{
var result = System.Windows.MessageBox.Show("Verzeichnis ist nicht leer.\nTrotzdem erstellen?", "Warnung", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.No) return;
}
var subdirnames = DirectoryConfig.getDefaultSubDirNames();
var dic = new Dictionary<string, string>();
foreach (var str in subdirnames)
{
dirinfo.CreateSubdirectory(str);
dic.Add(str, str);
}
var filecontent = JsonConvert.SerializeObject(dic);
var stream = File.Create(dirinfo.FullName + "\\config.hagvetcfg");
var streamwriter = new StreamWriter(stream);
streamwriter.Write(filecontent);
streamwriter.Close();
openDirectory(path);
}
/// <summary>
/// Changes the enabled state of some Tabs.
/// </summary>
/// <param name="enable">True, if they should be enabled</param>
public void setTabsEnabled(bool enable)
{
tab_documents.IsEnabled =
enableTabDocumentsTreeViewSelectionChangedEvent =
tab_pictures.IsEnabled =
enableTabDPicturesTreeViewSelectionChangedEvent =
enable;
}
/// <summary>
/// Fills the documents tab with content.
/// </summary>
public void createTabDocumentContent()
{
tab_documents_treeview.Items.Clear();
tab_documents_treeview.Items.AddRange(getTreeViewItems(DirectoryConfig.documentsDirInfo));
enableTabDocumentsTreeViewSelectionChangedEvent = true;
}
/// <summary>
/// Fills the pictures tab with content.
/// </summary>
public void createTabPicturesContent()
{
tab_pictures_treeview.Items.Clear();
tab_pictures_treeview.Items.AddRange(getTreeViewItems(DirectoryConfig.picturesDirInfo));
enableTabDPicturesTreeViewSelectionChangedEvent = true;
}
/// <summary>
/// Shows a FolderBrowserDialog to choose the location of the root directory.
/// </summary>
/// <returns>Path of the chosen directory.</returns>
public string chooseDirectory(bool showNewFolderButton = false)
{
var fbd = new FolderBrowserDialog();
fbd.Description = "Wähle das Verzeichnis des Datensystems aus!";
fbd.ShowNewFolderButton = showNewFolderButton;
var result = fbd.ShowDialog();
if (result.Equals(DialogResult.OK))
{
return fbd.SelectedPath;
}
return null;
}
/// <summary>
/// Loads the directory, validates its structure and initiates the tab content change.
/// </summary>
/// <param name="path">Path to root directory</param>
public void openDirectory(string path)
{
if (path == null) return;
var dirinfo = new DirectoryInfo(path);
//Breaks if the directory does not exist.
if (!dirinfo.Exists)
{
System.Windows.Forms.MessageBox.Show("Verzeichnis konnte nicht geladen werden.\nDer Pfad existiert nicht!", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DirectoryConfig.DirInfo = dirinfo;
//Break if the structure is invalid.
if (!DirectoryConfig.IsStructureValid())
{
System.Windows.Forms.MessageBox.Show("Verzeichnis konnte nicht geladen werden.\nDie Struktur ist fehlerhaft!", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
setTabsEnabled(false);
tabControl.SelectedIndex = 0;
createTabDocumentContent();
createTabPicturesContent();
setTabsEnabled(true);
}
/// <summary>
/// Gets all sub directories of dirinfo and puts them into hirarchical sorted TreeViewItem headers.
/// </summary>
/// <param name="dirinfo">Root directory for TreeViewItem headers</param>
/// <returns>A List of all TreeViewItems.</returns>
private List<TreeViewItem> getTreeViewItems(DirectoryInfo dirinfo)
{
var list = new List<TreeViewItem>();
foreach (var dir in dirinfo.GetDirectories())
{
var item = new TreeViewItem();
item.Header = dir.Name;
item.Items.AddRange(getTreeViewItems(dir));
list.Add(item);
}
return list;
}
#endregion
#region event handler
/// <summary>
/// Opens the directory whose path is stored in the 'tb_mainFolderPath' TextBox.
/// </summary>
private void event_openfolder(object sender, RoutedEventArgs e)
{
if(tb_mainFolderPath.Text == null || tb_mainFolderPath.Text == "")
{
openDirectory(chooseDirectory());
}
else
{
openDirectory(tb_mainFolderPath.Text);
}
}
/// <summary>
/// Executes 'chooseDirectory()' and put its return value into 'tb_mainFolderPath' TextBox's text.
/// </summary>
private void event_openOpenFolderWindow(object sender, RoutedEventArgs e)
{
var dirpath = chooseDirectory();
if (dirpath == null) return;
tb_mainFolderPath.Text = dirpath;
}
/// <summary>
/// Tab documents treeview selection changed event handler
/// </summary>
private void tab_documents_treeview_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (!enableTabDocumentsTreeViewSelectionChangedEvent) return;
tab_documents_docview.Items.Clear();
var item = (TreeViewItem)tab_documents_treeview.SelectedItem;
var path = "";
do
{
path = item.Header + "\\" + path;
}
while ((item.Parent is TreeViewItem) && (item = (TreeViewItem)item.Parent) == item);
path = DirectoryConfig.documentsDirInfo.FullName + "\\" + path;
var dirinfo = new DirectoryInfo(path);
var docs = new List<object>();
var ext = new List<string>() { ".docx", ".docm" };
foreach (var file in dirinfo.GetFiles())
{
if (ext.Contains(file.Extension))
{
docs.Add(new ListViewFileItem(file));
}
}
tab_documents_docview.Items.AddRange(docs);
}
/// <summary>
/// Creates a preview of the selected document.
/// </summary>
private void tab_documents_docview_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
tab_documents_preview.FileName = ((ListViewFileItem)tab_documents_docview.SelectedItem).finfo.FullName;
}
/// <summary>
/// Equal widths of all columns in a ListView
/// </summary>
private void listview_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (!e.WidthChanged) return;
var gridView = (GridView)((System.Windows.Controls.ListView)sender).View;
var width = e.NewSize.Width;
var colCount = gridView.Columns.Count;
foreach (var col in gridView.Columns)
{
col.Width = width / colCount;
}
}
private void tab_pictures_treeview_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
}
#endregion
}
} |
namespace ServiceBase.Mvc.ModelBinding
{
// .AddMvc(options =>
// {
// options.ModelBinderProviders
// .Insert(0, new TrimStringModelBinderProvider());
// })
using System;
using Microsoft.AspNetCore.Mvc.ModelBinding;
public class TrimStringModelBinderProvider : IModelBinderProvider
{
private readonly IModelBinder binder = new TrimStringModelBinder();
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
return context.Metadata.ModelType == typeof(String) ? binder : null;
}
}
}
|
/**********************************************************************************
Simple Smart Types Lite
https://github.com/dgakh/SSTypes
-----------------------
The MIT License (MIT)
Copyright (c) 2016 Dmitriy Gakh ( dmgakh@gmail.com ).
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**********************************************************************************/
namespace SSTypes
{
/// <summary>
/// Class containing useful fields, methods, and properties need for other classes or
/// for general purposes.
/// </summary>
public static class Helper
{
/// <summary>
/// Combines two int hash values into one.
/// </summary>
/// <param name="code_1">First code to combine.</param>
/// <param name="code_2">Second code to combine.</param>
/// <returns>Combined hash code.</returns>
public static int CombineHashCodes(int code_1, int code_2)
{
int result;
unchecked
{
result = (code_1 << 5) + 3 + code_1 ^ code_2;
}
return result;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ShadowAPI.Services
{
//public enum DiceResult :byte
//{
// CriticalGlitch
//}
public interface IShadowRunRoller
{
int[] Roll(int dice);
int[] Roll(int dice, int faces);
}
public class ShadowRunRoller : IShadowRunRoller
{
private int _defaultDieFace;
private Random _random;
private int[] _lastRoll;
public ShadowRunRoller()
{
_defaultDieFace = 6;
_random = new Random();
_lastRoll = new int[0];
}
public int[] Roll(int dice)
{
return Roll(dice, _defaultDieFace);
}
public int[] Roll(int dice, int face)
{
int[] result = new int[dice];
for (int i = 0; i < dice; i++)
{
result[i] = _random.Next(6) + 1;
}
return result;
}
}
}
|
using NUnit.Framework;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using TechTalk.SpecFlow;
namespace ZiZhuJY.PhantomJsWrapper.Tests
{
[Binding]
public class PhantomJsWorkerSteps
{
private string url = string.Empty;
private PhantomJsWorker.PhantomJsExecutionResult executionResult;
[Given(@"the web page url is ""(.*)""")]
public void GivenTheWebPageUrlIs(string webPageUrl)
{
url = webPageUrl;
}
[When(@"I grab it")]
public void WhenIGrabIt()
{
executionResult = PhantomJsWorker.GrabWebPageToPDF(url);
}
[Then(@"there I will get informed with the pdf path")]
public void ThenThereIWillGetInformedWithThePdfPath()
{
Trace.WriteLine(string.Format("Start Info Arguments:\r\n{0}", executionResult.StartInfo.Arguments));
Trace.WriteLine(string.Format("Standard Output:\r\n{0}", executionResult.OutputMessage));
Trace.WriteLine(string.Format("Standard Error:\r\n{0}", executionResult.ErrorMessage));
Assert.IsTrue(!string.IsNullOrEmpty(executionResult.OutputFilePaths[0]));
var regex = new Regex(@"GrabWebPageToPDF_[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\.pdf");
//Assert.IsTrue(regex.IsMatch(_executionOutput.OutputFilePaths[0]),
//string.Format("Actual output file path is : {0}", _executionOutput.OutputFilePaths[0]));
Assert.IsTrue(File.Exists(executionResult.OutputFilePaths[0]));
File.Delete(executionResult.OutputFilePaths[0]);
}
}
}
|
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using TQVaultAE.Domain.Contracts.Services;
using TQVaultAE.Domain.Entities;
using TQVaultAE.GUI.Helpers;
using TQVaultAE.GUI.Models;
using TQVaultAE.Presentation;
namespace TQVaultAE.GUI.Components;
public partial class HighlightFilters : UserControl
{
private LinkLabel _link;
public SessionContext UserContext { get; internal set; }
public ITranslationService TranslationService { get; internal set; }
public IFontService FontService { get; internal set; }
public HighlightFilters()
{
InitializeComponent();
DoubleBuffered = true;
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
BackgroundImageLayout = ImageLayout.Stretch;
BackgroundImage = Resources.caravan_bg;
}
internal void InitializeFilters()
{
this.ProcessAllControls(c => c.Font = FontService.GetFontLight(10F));
toolTip.SetToolTip(numericUpDownMinDex, Resources.HighlightFiltersZeroToIgnore);
toolTip.SetToolTip(numericUpDownMinInt, Resources.HighlightFiltersZeroToIgnore);
toolTip.SetToolTip(numericUpDownMinLvl, Resources.HighlightFiltersZeroToIgnore);
toolTip.SetToolTip(numericUpDownMinStr, Resources.HighlightFiltersZeroToIgnore);
toolTip.SetToolTip(numericUpDownMaxDex, Resources.HighlightFiltersZeroToIgnore);
toolTip.SetToolTip(numericUpDownMaxInt, Resources.HighlightFiltersZeroToIgnore);
toolTip.SetToolTip(numericUpDownMaxLvl, Resources.HighlightFiltersZeroToIgnore);
toolTip.SetToolTip(numericUpDownMaxStr, Resources.HighlightFiltersZeroToIgnore);
InitRarity();
InitType();
InitOrigin();
// Translate
scalingCheckBoxMin.Text = $"{Resources.GlobalMin} {Resources.GlobalRequirements} :";
scalingCheckBoxMax.Text = $"{Resources.GlobalMax} {Resources.GlobalRequirements} :";
scalingLabelMaxLvl.Text =
scalingLabelMinLvl.Text = TranslationService.TranslateXTag("tagMenuImport05");
scalingLabelMaxStr.Text =
scalingLabelMinStr.Text = TranslationService.TranslateXTag("Strength");
scalingLabelMaxDex.Text =
scalingLabelMinDex.Text = TranslationService.TranslateXTag("Dexterity");
scalingLabelMaxInt.Text =
scalingLabelMinInt.Text = TranslationService.TranslateXTag("Intelligence");
scalingCheckBoxHavingCharm.Text = Resources.SearchHavingCharm;
scalingCheckBoxHavingRelic.Text = Resources.SearchHavingRelic;
scalingCheckBoxHavingPrefix.Text = Resources.SearchHavingPrefix;
scalingCheckBoxHavingSuffix.Text = Resources.SearchHavingSuffix;
scalingCheckBoxSetItem.Text = Resources.SearchSetItem;
buttonReset.Text = TranslationService.TranslateXTag("tagSkillReset");
buttonApply.Text = TranslationService.TranslateXTag("tagMenuButton07");
}
private void InitOrigin()
{
scalingCheckedListBoxOrigin.Items.Clear();// Remove design mode items
var list = new ItemOrigin[] {
new ItemOrigin{
Value = GameDlc.TitanQuest,
DisplayName = TranslationService.Translate(GameDlc.TitanQuest)
},
new ItemOrigin{
Value = GameDlc.ImmortalThrone,
DisplayName = TranslationService.Translate(GameDlc.ImmortalThrone)
},
new ItemOrigin{
Value = GameDlc.Ragnarok,
DisplayName = TranslationService.Translate(GameDlc.Ragnarok)
},
new ItemOrigin{
Value = GameDlc.Atlantis,
DisplayName = TranslationService.Translate(GameDlc.Atlantis)
},
new ItemOrigin{
Value = GameDlc.EternalEmbers,
DisplayName = TranslationService.Translate(GameDlc.EternalEmbers)
},
};
// Compute item space (ColumnWidth)
int maxWidth = list.Select(i =>
TextRenderer.MeasureText(
i.DisplayName
, scalingCheckedListBoxOrigin.Font
, scalingCheckedListBoxOrigin.Size
, TextFormatFlags.SingleLine
).Width
).Max();
maxWidth += SystemInformation.VerticalScrollBarWidth;// Add this for the size of the checkbox in front of the text
scalingCheckedListBoxOrigin.ColumnWidth = maxWidth;
scalingCheckedListBoxOrigin.Items.AddRange(list);
}
private void InitType()
{
scalingCheckedListBoxTypes.Items.Clear();// Remove design mode items
var list = new ItemType[] {
new ItemType{
Value = Item.ICLASS_HEAD,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_HEAD)).Trim(' ', ':')
},
new ItemType{
Value = Item.ICLASS_FOREARM,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_FOREARM)).Trim(' ', ':')
},
new ItemType{
Value = Item.ICLASS_UPPERBODY,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_UPPERBODY)).Trim(' ', ':')
},
new ItemType{
Value = Item.ICLASS_LOWERBODY,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_LOWERBODY)).Trim(' ', ':')
},
new ItemType{
Value = Item.ICLASS_AXE,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_AXE))
},
new ItemType{
Value = Item.ICLASS_MACE,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_MACE))
},
new ItemType{
Value = Item.ICLASS_SWORD,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_SWORD))
},
new ItemType{
Value = Item.ICLASS_SHIELD,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_SHIELD))
},
new ItemType{
Value = Item.ICLASS_RANGEDONEHAND,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_RANGEDONEHAND), true)
},
new ItemType{
Value = Item.ICLASS_BOW,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_BOW))
},
new ItemType{
Value = Item.ICLASS_SPEAR,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_SPEAR))
},
new ItemType{
Value = Item.ICLASS_STAFF,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_STAFF)).Trim(' ', ':')
},
new ItemType{
Value = Item.ICLASS_AMULET,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_AMULET))
},
new ItemType{
Value = Item.ICLASS_RING,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_RING))
},
new ItemType{
Value = Item.ICLASS_ARTIFACT,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_ARTIFACT))
},
new ItemType{
Value = Item.ICLASS_FORMULA,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_FORMULA))
},
new ItemType{
Value = Item.ICLASS_RELIC,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_RELIC))
},
new ItemType{
Value = Item.ICLASS_CHARM,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_CHARM))
},
new ItemType{
Value = Item.ICLASS_SCROLL,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_SCROLL))
},
new ItemType{
Value = string.Join("|", Item.ICLASS_POTIONMANA, Item.ICLASS_POTIONHEALTH, Item.ICLASS_SCROLL_ETERNAL),
DisplayName = TranslationService.TranslateXTag("tagTutorialTip14Title")
},
new ItemType{
Value = Item.ICLASS_QUESTITEM,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_QUESTITEM))
},
new ItemType{
Value = Item.ICLASS_EQUIPMENT,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_EQUIPMENT)).Trim(' ', '~')
},
new ItemType{
Value = Item.ICLASS_DYE,
DisplayName = TranslationService.TranslateXTag(Item.GetClassTagName(Item.ICLASS_DYE))
},
};
// Compute item space (ColumnWidth)
int maxWidth = list.Select(i =>
TextRenderer.MeasureText(
i.DisplayName
, scalingCheckedListBoxTypes.Font
, scalingCheckedListBoxTypes.Size
, TextFormatFlags.SingleLine
).Width
).Max();
maxWidth += SystemInformation.VerticalScrollBarWidth;// Add this for the size of the checkbox in front of the text
scalingCheckedListBoxTypes.ColumnWidth = maxWidth;
scalingCheckedListBoxTypes.Items.AddRange(list);
}
private void InitRarity()
{
scalingCheckedListBoxRarity.Items.Clear();// Remove design mode items
var listRarity = new ItemRarity[] {
new ItemRarity(){
Value = Rarity.Broken,
DisplayName = TranslationService.Translate(Rarity.Broken)
},
new ItemRarity(){
Value = Rarity.Mundane,
DisplayName = TranslationService.Translate(Rarity.Mundane)
},
new ItemRarity(){
Value = Rarity.Common,
DisplayName = TranslationService.Translate(Rarity.Common)
},
new ItemRarity(){
Value = Rarity.Rare,
DisplayName = TranslationService.Translate(Rarity.Rare)
},
new ItemRarity(){
Value = Rarity.Epic,
DisplayName = TranslationService.Translate(Rarity.Epic)
},
new ItemRarity(){
Value = Rarity.Legendary,
DisplayName = TranslationService.Translate(Rarity.Legendary)
},
};
// Compute item space (ColumnWidth)
var maxWidth = listRarity.Select(i =>
TextRenderer.MeasureText(
i.DisplayName
, scalingCheckedListBoxRarity.Font
, scalingCheckedListBoxRarity.Size
, TextFormatFlags.SingleLine
).Width
).Max();
maxWidth += SystemInformation.VerticalScrollBarWidth;// Add this for the size of the checkbox in front of the text
scalingCheckedListBoxRarity.ColumnWidth = maxWidth;
scalingCheckedListBoxRarity.Items.AddRange(listRarity);
}
internal void ResetAll()
{
ResetNumeric();
scalingCheckBoxMax.Checked =
scalingCheckBoxMin.Checked =
scalingCheckBoxSetItem.Checked =
scalingCheckBoxHavingCharm.Checked =
scalingCheckBoxHavingRelic.Checked =
scalingCheckBoxHavingPrefix.Checked =
scalingCheckBoxHavingSuffix.Checked = false;
ClearSelected(scalingCheckedListBoxTypes);
ClearSelected(scalingCheckedListBoxRarity);
ClearSelected(scalingCheckedListBoxOrigin);
}
private static void ClearSelected(ScalingCheckedListBox listbox)
{
listbox.ClearSelected();
for (int i = 0; i < listbox.Items.Count; i++)
listbox.SetItemChecked(i, false);
}
internal void ResetNumeric()
{
numericUpDownMaxDex.Value =
numericUpDownMaxInt.Value =
numericUpDownMaxLvl.Value =
numericUpDownMaxStr.Value =
numericUpDownMinDex.Value =
numericUpDownMinInt.Value =
numericUpDownMinLvl.Value =
numericUpDownMinStr.Value = 0;
}
/// <summary>
/// Anchor link
/// </summary>
internal LinkLabel Link
{
set
{
_link = value;
AdjustLocation();
}
}
private void AdjustLocation()
{
// Adjust location
var frm = FindForm();
var linklocation = frm.PointToClient(_link.PointToScreen(Point.Empty));
Location = new Point(linklocation.X, linklocation.Y - Height);
}
private void buttonReset_Click(object sender, EventArgs e)
{
var frm = FindForm();
ResetAll();
UserContext.HighlightFilter = null;
_link.LinkVisited = false;
Visible = false;
UserContext.FindHighlight();
frm.Refresh();
}
private void buttonSave_Click(object sender, EventArgs e)
{
var frm = FindForm();
var filter = new HighlightFilterValues
{
MaxLvl = (int)numericUpDownMaxLvl.Value,
MaxDex = (int)numericUpDownMaxDex.Value,
MaxInt = (int)numericUpDownMaxInt.Value,
MaxStr = (int)numericUpDownMaxStr.Value,
MinLvl = (int)numericUpDownMinLvl.Value,
MinDex = (int)numericUpDownMinDex.Value,
MinInt = (int)numericUpDownMinInt.Value,
MinStr = (int)numericUpDownMinStr.Value,
MaxRequierement = scalingCheckBoxMax.Checked,
MinRequierement = scalingCheckBoxMin.Checked,
ClassItem = scalingCheckedListBoxTypes.CheckedItems.OfType<ItemType>().SelectMany(x => x.Value.Split('|')).ToList(),
Rarity = scalingCheckedListBoxRarity.CheckedItems.OfType<ItemRarity>().Select(x => x.Value).ToList(),
Origin = scalingCheckedListBoxOrigin.CheckedItems.OfType<ItemOrigin>().Select(x => x.Value).ToList(),
HavingPrefix = scalingCheckBoxHavingPrefix.Checked,
HavingSuffix = scalingCheckBoxHavingSuffix.Checked,
HavingRelic = scalingCheckBoxHavingRelic.Checked,
HavingCharm = scalingCheckBoxHavingCharm.Checked,
IsSetItem = scalingCheckBoxSetItem.Checked,
};
if (filter.MaxRequierement || filter.MinRequierement || filter.HavingPrefix || filter.HavingSuffix || filter.HavingRelic || filter.HavingCharm || filter.IsSetItem
|| filter.ClassItem.Any() || filter.Rarity.Any() || filter.Origin.Any())
{
UserContext.HighlightFilter = filter;
_link.LinkVisited = true;
Visible = false;
UserContext.FindHighlight();
frm.Refresh();
return;
}
// No filters
UserContext.HighlightFilter = null;
_link.LinkVisited = false;
Visible = false;
UserContext.FindHighlight();
frm.Refresh();
}
private void numericUpDownMinLvl_ValueChanged(object sender, EventArgs e)
{
scalingCheckBoxMin.Checked = true;
}
private void numericUpDownMaxLvl_ValueChanged(object sender, EventArgs e)
{
scalingCheckBoxMax.Checked = true;
}
}
|
/*
DotNetMQ - A Complete Message Broker For .NET
Copyright (C) 2011 Halil ibrahim KALKAN
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using MDS.Communication.Messages;
namespace MDS.Organization.Routing
{
/// <summary>
/// Sequential distribution strategy.
/// According to this strategy, a message is routed one of available destinations sequentially according to destination's RouteFactor.
/// For example, if,
///
/// - Destination-A has a RouteFactor of 4
/// - Destination-B has a RouteFactor of 1
///
/// Then, 4 messages are sent to Destination-A, 1 message is sent to Destination-B sequentially.
/// </summary>
internal class SequentialDistribution : DistributionStrategyBase, IDistributionStrategy
{
/// <summary>
/// Total count of all RouteFactors of Destinations and calculated by Reset method.
/// </summary>
private int _totalCount;
/// <summary>
/// Current routing number. It is used to determine the next routing destination.
/// For example, if,
///
/// - Destination-A has a RouteFactor of 4
/// - Destination-B has a RouteFactor of 3
/// - Destination-C has a RouteFactor of 3
///
/// and _currentNumber is 5, then destination is Destination-B.
/// </summary>
private int _currentNumber;
/// <summary>
/// Creates a new SequentialDistribution object.
/// </summary>
/// <param name="routingRule">Reference to RoutingRule object that uses this distribution strategy to route messages</param>
public SequentialDistribution(RoutingRule routingRule)
: base(routingRule)
{
Reset();
}
/// <summary>
/// Initializes and Resets distribution strategy.
/// </summary>
public void Reset()
{
_totalCount = 0;
foreach (var destination in RoutingRule.Destinations)
{
_totalCount += destination.RouteFactor;
}
}
/// <summary>
/// Sets the destination of a message according to distribution strategy.
/// </summary>
/// <param name="message">Message to set it's destination</param>
public void SetDestination(MDSDataTransferMessage message)
{
//Return, if no destination exists
if (_totalCount == 0 || RoutingRule.Destinations.Length <= 0)
{
return;
}
//Find next destination and set
var currentTotal = 0;
foreach (var destination in RoutingRule.Destinations)
{
currentTotal += destination.RouteFactor;
if (_currentNumber < currentTotal)
{
SetMessageDestination(message, destination);
break;
}
}
//Increase _currentNumber
if ((++_currentNumber) >= _totalCount)
{
_currentNumber = 0;
}
}
}
}
|
using BUKEP.TESTS.DRIVER.Enums;
using OpenQA.Selenium.Chrome;
namespace BUKEP.TESTS.DRIVER.Managers.AsuBukep
{
public class JavaScriptManager
{
private static ChromeDriver _driver;
public JavaScriptManager(ChromeDriver chromeDriver)
{
_driver = chromeDriver;
}
/// <summary>
/// Получить название узла в структурном дереве
/// </summary>
/// <param name="elementId">Идентификатор узла</param>
/// <returns>Наименование узла</returns>
public static string GetBranchNameInStructTree(string elementId)
{
return _driver.ExecuteScript($"return document.getElementById('{elementId}')" +
".parentElement.nextElementSibling.innerText").ToString();
}
/// <summary>
/// Получить зоголовок фрейма
/// </summary>
/// <param name="classNames">Классы элемента</param>
/// <returns>Наименование заголовка</returns>
public string GetTitleFrame(string classNames)
{
return _driver.ExecuteScript($"return document.getElementsByClassName('{classNames}')" +
$"[0].previousElementSibling.previousElementSibling.textContent").ToString();
}
/// <summary>
/// Имитация нажатия кнопки Отмена, в alert уведомлении
/// </summary>
public void AlertToDismiss()
{
ErrorLoggingManager.SaveAction(ErrorLoggingManager.GetModel(TypeOperation.Click, "Отмена"));
_driver.SwitchTo().Alert().Dismiss();
ErrorLoggingManager.ErrorCheck();
}
/// <summary>
/// Имитация нажатия кнопки Ок, в alert уведомлении
/// </summary>
public void AlertToAccept()
{
ErrorLoggingManager.SaveAction(ErrorLoggingManager.GetModel(TypeOperation.Click, "Ок"));
_driver.SwitchTo().Alert().Accept();
ErrorLoggingManager.ErrorCheck();
}
}
}
|
using Game;
using OculusSampleFramework;
using UnityEngine;
namespace Player
{
public class AssaultRifleGrabber : MonoBehaviour
{
public static AssaultRifleGrabber Instance;
private void Awake()
{
if (Instance)
{
Destroy(this);
}
else
{
Instance = this;
}
}
[SerializeField] private OVRInput.Button rifleTransformButton;
public OVRGrabber rightHand;
public OVRGrabber leftHand;
[SerializeField] private Transform tempRightObjectParent;
[SerializeField] private Transform tempLeftObjectParent;
[SerializeField] private DistanceGrabbable rifle;
[HideInInspector] public bool isUsingRifle;
private DistanceGrabbable _rightObject;
private DistanceGrabbable _leftObject;
// Start is called before the first frame update
void Start()
{
rifle.SetObjectActivation(false);
SetRifleParent(GameSettings.Instance.isRightHand);
}
// Update is called once per frame
void Update()
{
if (!isUsingRifle && (OVRInput.Get(OVRInput.RawButton.RHandTrigger, rightHand.GetController()) && OVRInput.Get(OVRInput.RawButton.LHandTrigger, leftHand.GetController())))
{
//Get the Assault Rifle
if(rightHand.grabbedObject) _rightObject = (DistanceGrabbable)rightHand.grabbedObject;
if(leftHand.grabbedObject) _leftObject = (DistanceGrabbable)leftHand.grabbedObject;
if(_rightObject) _rightObject.SetObjectActivation(false);
if(_leftObject) _leftObject.SetObjectActivation(false);
if (GameSettings.Instance.isRightHand)
{
if(_rightObject) _rightObject.transform.SetParent(tempRightObjectParent);
rightHand.GrabBegin(rifle.GetComponent<DistanceGrabbable>());
}
else
{
if(_leftObject) _leftObject.transform.SetParent(tempLeftObjectParent);
leftHand.GrabBegin(rifle.GetComponent<DistanceGrabbable>());
}
rifle.SetObjectActivation(true);
isUsingRifle = true;
rightHand.isUsingRifle = true;
leftHand.isUsingRifle = true;
}
else if (isUsingRifle && (OVRInput.GetUp(rifleTransformButton, rightHand.GetController()) ||
OVRInput.GetUp(rifleTransformButton, leftHand.GetController())))
{
rightHand.isUsingRifle = false;
leftHand.isUsingRifle = false;
if (GameSettings.Instance.isRightHand)
{
rightHand.GrabEnd(true);
//if(_rightObject) _rightObject.transform.SetParent(null);
rightHand.GrabBegin(_rightObject);
}
else
{
leftHand.GrabEnd(true);
//if(_leftObject) _leftObject.transform.SetParent(null);
leftHand.GrabBegin(_leftObject);
}
rifle.SetObjectActivation(false);
isUsingRifle = false;
if(_rightObject) _rightObject.SetObjectActivation(true);
if(_leftObject) _leftObject.SetObjectActivation(true);
_rightObject = null;
_leftObject = null;
}
}
public void SetRifleParent(bool isRightHand)
{
//Parent the assault rifle to the right hand anchor, depending on the users primary hand choice
rifle.transform.SetParent(isRightHand ? tempRightObjectParent : tempLeftObjectParent);
}
}
}
|
using System;
class MainClass
{
public static void Main ()
{
Console.WriteLine ("N:");
int n = Int32.Parse (Console.ReadLine ());
Console.WriteLine ("K:");
int k = Int32.Parse (Console.ReadLine ());
long result = 0;
long nFactorael = 1;
long kFactorael = 1;
if (k > 1 && n > k && n < 100) {
for (int i = 1; i <= n; i++) {
nFactorael = nFactorael * i;
}
for (int j = 1; j <= k; j++) {
kFactorael = kFactorael * j;
}
result = nFactorael / kFactorael;
Console.WriteLine ();
Console.WriteLine (result);
} else {
Console.WriteLine ("Not [1 < k < n < 100] Start again!!!");
}
}
} |
using FatCat.Nes.OpCodes.Branching;
using JetBrains.Annotations;
namespace FatCat.Nes.Tests.OpCodes.Branching
{
[UsedImplicitly]
public class BranchIfNegativeTests : BranchTests
{
protected override string ExpectedName => "BMI";
protected override CpuFlag Flag => CpuFlag.Negative;
protected override bool FlagState => true;
public BranchIfNegativeTests() => opCode = new BranchIfNegative(cpu, addressMode);
}
} |
using System;
using System.Linq;
using System.Text;
namespace TQVaultAE.Domain.Entities
{
public class SkillRecord
{
internal static readonly Encoding Encoding1252 = Encoding.GetEncoding(1252);
public string skillName { get; set; }
public int skillLevel { get; set; }
public int skillEnabled { get; set; }
public int skillSubLevel { get; set; }
public int skillActive { get; set; }
public int skillTransition { get; set; }
/// <summary>
/// Binary serialize
/// </summary>
/// <returns></returns>
public byte[] ToBinary(int beginBlockValue, int endBlockValue)
{
var array = new[] {
BitConverter.GetBytes("begin_block".Length),
Encoding1252.GetBytes("begin_block"),
BitConverter.GetBytes(beginBlockValue),
BitConverter.GetBytes(nameof(skillName).Length),
Encoding1252.GetBytes(nameof(skillName)),
BitConverter.GetBytes(skillName.Length),
Encoding1252.GetBytes(skillName),
BitConverter.GetBytes(nameof(skillLevel).Length),
Encoding1252.GetBytes(nameof(skillLevel)),
BitConverter.GetBytes(skillLevel),
BitConverter.GetBytes(nameof(skillEnabled).Length),
Encoding1252.GetBytes(nameof(skillEnabled)),
BitConverter.GetBytes(skillEnabled),
BitConverter.GetBytes(nameof(skillSubLevel).Length),
Encoding1252.GetBytes(nameof(skillSubLevel)),
BitConverter.GetBytes(skillSubLevel),
BitConverter.GetBytes(nameof(skillActive).Length),
Encoding1252.GetBytes(nameof(skillActive)),
BitConverter.GetBytes(skillActive),
BitConverter.GetBytes(nameof(skillTransition).Length),
Encoding1252.GetBytes(nameof(skillTransition)),
BitConverter.GetBytes(skillTransition),
BitConverter.GetBytes("end_block".Length),
Encoding1252.GetBytes("end_block"),
BitConverter.GetBytes(endBlockValue),
}.SelectMany(arr => arr).ToArray();
return array;
}
}
}
|
using System.Threading.Tasks;
using Meziantou.Analyzer.Rules;
using TestHelper;
using Xunit;
namespace Meziantou.Analyzer.Test.Rules;
public sealed class DoNotRemoveOriginalExceptionFromThrowStatementAnalyzerTests
{
private static ProjectBuilder CreateProjectBuilder()
{
return new ProjectBuilder()
.WithAnalyzer<DoNotRemoveOriginalExceptionFromThrowStatementAnalyzer>()
.WithCodeFixProvider<DoNotRemoveOriginalExceptionFromThrowStatementFixer>();
}
[Fact]
public async Task NoDiagnostic()
{
const string SourceCode = @"
class Test
{
internal void Sample()
{
throw new System.Exception();
try
{
throw new System.Exception();
}
catch (System.Exception ex)
{
throw new System.Exception(""test"", ex);
}
}
}
";
await CreateProjectBuilder()
.WithSourceCode(SourceCode)
.ValidateAsync();
}
[Fact]
public async Task ShouldReportDiagnostic()
{
const string SourceCode = @"
class Test
{
internal void Sample()
{
try
{
}
catch (System.Exception ex)
{
_ = ex;
[||]throw ex;
}
}
}
";
const string CodeFix = @"
class Test
{
internal void Sample()
{
try
{
}
catch (System.Exception ex)
{
_ = ex;
throw;
}
}
}
";
await CreateProjectBuilder()
.WithSourceCode(SourceCode)
.ShouldFixCodeWith(CodeFix)
.ValidateAsync();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadMonitorWaitPulse
{
class Program
{
public static bool finished = false;
public static bool thread1Waiting = false;
public static bool thread2Waiting = false;
static void Main(string[] args)
{
MyNumber zahl = new MyNumber();
ProduceNumber prod = new ProduceNumber(zahl);
ConsumeNumber cons = new ConsumeNumber(zahl);
Thread thread1, thread2;
// Threads instanzieren
thread1 = new Thread(new ThreadStart(prod.MakeNumber));
thread2 = new Thread(new ThreadStart(cons.GetNumber));
// Threads starten
thread1.Start();
thread2.Start();
Console.ReadLine();
}
}
}
|
using System;
using System.Linq;
using System.Text;
using Castle.Core.Logging;
using Castle.DynamicProxy;
namespace LoggingAopCastle.LogHelpers
{
public static class LogExtensions
{
public static void LogError(this ILogger logger, IInvocation invocation, Exception ex)
{
var invocationString = logger.CreateInvocationLogString(invocation);
logger.ErrorFormat(invocationString +
Environment.NewLine + Environment.NewLine + "~~ Start of exception report ~~" +
Environment.NewLine + Environment.NewLine +
"Error occurred whilst executing: " + invocationString + Environment.NewLine +
"Exception type: " + ex.GetType().Name + Environment.NewLine +
"Message: " + ex.Message + Environment.NewLine +
"------------------------" + Environment.NewLine + "Contents of stack trace:" +
Environment.NewLine + ex.StackTrace + Environment.NewLine +
"------------------------" + Environment.NewLine + Environment.NewLine +
"~~ End of exception report ~~" + Environment.NewLine);
}
public static String CreateInvocationLogString(this ILogger logger, IInvocation invocation)
{
StringBuilder sb = new StringBuilder(100);
sb.AppendFormat("{0}.{1}(", invocation.TargetType.Name, invocation.Method.Name);
foreach (object argument in invocation.Arguments)
{
String argumentDescription = argument == null ? "null" : logger.DumpObject(argument);
sb.Append(argumentDescription).Append(",");
}
if (invocation.Arguments.Count() > 0) sb.Length--;
sb.Append(")");
return sb.ToString();
}
private static string DumpObject(this ILogger logger, object argument)
{
Type objtype = argument.GetType();
return objtype.Name + " " + "'" + argument + "'";
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using Bindable.Linq.Dependencies;
using Bindable.Linq.Interfaces.Events;
using Bindable.Linq.Threading;
namespace Bindable.Linq.Interfaces
{
/// <summary>
/// An interface implemented by all Bindable LINQ bindable collections.
/// </summary>
public interface IBindableCollection : IEnumerable, IRefreshable, INotifyCollectionChanged, INotifyPropertyChanged, IAcceptsDependencies, IDisposable
{
/// <summary>
/// Gets the dispatcher.
/// </summary>
/// <value>The dispatcher.</value>
IDispatcher Dispatcher { get; }
/// <summary>
/// Gets the count of items in the collection.
/// </summary>
int Count { get; }
/// <summary>
/// Gets a value indicating whether this instance has already evaluated.
/// </summary>
/// <value>
/// <c>true</c> if this instance has evaluated; otherwise, <c>false</c>.
/// </value>
bool HasEvaluated { get; }
/// <summary>
/// Evaluates this instance.
/// </summary>
void Evaluate();
}
/// <summary>
/// An interface implemented by all Bindable LINQ bindable collections.
/// </summary>
/// <typeparam name="TElement">The type of the element.</typeparam>
public interface IBindableCollection<TElement> : IEnumerable<TElement>, IBindableCollection
{
/// <summary>
/// Gets the <typeparamref name="TElement"/> at the specified index.
/// </summary>
/// <value></value>
TElement this[int index] { get; }
/// <summary>
/// Occurs when the collection is being evaluated (GetEnumerator() is called) for the first time, just before it returns
/// the results, to provide insight into the items being evaluated. This allows consumers to iterate the items in a collection
/// just before they are returned to the caller, while still enabling delayed execution of queries.
/// </summary>
event EvaluatingEventHandler<TElement> Evaluating;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PROJECT.SERV.Model.Adm
{
public class TCP_Adm_UsuPerArea
{
public int araclave { set; get; }
public int usuclave { set; get; }
public int prlclave { set; get; }
public TCP_Adm_UsuPerArea () {}
public TCP_Adm_UsuPerArea (
int araclave, int usuclave, int prlclave
)
{
this.araclave = araclave;
this.usuclave = usuclave;
this.prlclave = prlclave;
}
}
}
|
using Accounting.DataAccess;
using Accounting.Entity;
using Accounting.Utility;
using AccSys.Web.WebControls;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using Tools;
namespace AccSys.Web
{
public partial class frmRoles : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
LoadRoles();
}
}
catch (Exception ex)
{
lblMsg.Text = ex.CustomDialogMessage();
}
}
private void LoadRoles()
{
using (var connection = new SqlConnection(ConnectionHelper.DefaultConnectionString))
{
connection.Open();
DataTable dt = new DataTable();
dt = new DaRole().GetRoles(connection);
gvData.DataSource = dt;
gvData.DataBind();
connection.Close();
}
}
protected void lbtnDelete_Click(object sender, EventArgs e)
{
try
{
var lblRoleId = ((LinkButton)sender).NamingContainer.FindControl("lblRoleId");
if (lblRoleId != null)
{
var roleId = Convert.ToInt32(((Label)lblRoleId).Text);
new DaRole().DeleteRole(roleId);
LoadRoles();
lblMsg.Text = UIMessage.Message2User("Role deleted successfully", UserUILookType.Success);
}
}
catch (Exception ex)
{
lblMsg.Text = ex.CustomDialogMessage();
}
}
protected void btnCreate_Click(object sender, EventArgs e)
{
try
{
var role = new Role()
{
RoleId = Convert.ToInt32(lblRoleId.Text),
RoleName = txtRoleName.Text.Trim()
};
new DaRole().SaveUpdateRole(role);
LoadRoles();
lblMsg.Text = UIMessage.Message2User("Role saved successfully", UserUILookType.Success);
btnReset_Click(null, e);
}
catch (Exception ex)
{
lblMsg.Text = ex.CustomDialogMessage();
}
}
protected void btnReset_Click(object sender, EventArgs e)
{
lblRoleId.Text = "0";
txtRoleName.Text = "";
btnCreate.Text = "Create Role";
if (sender != null)
{
lblMsg.Text = "";
}
}
protected void lbtnEdit_Click(object sender, EventArgs e)
{
try
{
using (var connection = new SqlConnection(ConnectionHelper.DefaultConnectionString))
{
connection.Open();
Label lblId = (Label)((LinkButton)sender).NamingContainer.FindControl("lblRoleId");
lblRoleId.Text = lblId.Text;
Label lblRoleName = (Label)((LinkButton)sender).NamingContainer.FindControl("lblRoleName");
txtRoleName.Text = lblRoleName.Text;
btnCreate.Text = "Update Role";
lblMsg.Text = "";
connection.Close();
}
}
catch (Exception ex)
{
lblMsg.Text = ex.CustomDialogMessage();
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Dentist.Models;
using Dentist.Models.Patient;
using Dentist.ViewModels;
using AutoMapper.QueryableExtensions;
using System.Web.Http.OData;
namespace Dentist.Controllers
{
public class PatientNotesApiController : BaseApiController
{
// GET: api/PatientNotesApi
[EnableQuery]
public IQueryable<PatientNoteDto> GetPatientNotes()
{
var query = ReadContext.Set<PatientNote>().Include(x => x.Notes).ProjectTo<PatientNoteDto>().OrderByDescending(x=>x.RecordedDate);
return query;
}
//// GET: api/PatientNotesApi/5
//[ResponseType(typeof(PatientNoteDto))]
//public IHttpActionResult GetPatientNote(int id)
//{
// return NotFound();
// PatientNote patientNote = ReadContext.PatientNotes.Include(x => x.Notes).FirstOrDefault(x => x.Id == id);
// if (patientNote == null)
// {
// return NotFound();
// }
// var patientNoteDto = AutoMapper.Mapper.Map<PatientNoteDto>(patientNote);
// return Ok(patientNoteDto);
//}
// PUT: api/PatientNotesApi/5
[ResponseType(typeof(void))]
public IHttpActionResult PutPatientNote(PatientNoteDto patientNoteDto)
{
//return NotFound();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var patientNoteEnvelop = WriteContext.PatientNotes.Find(patientNoteDto.Id);
if (patientNoteEnvelop == null)
{
return NotFound();
}
// delete notes
var deletedNotesDto = patientNoteDto.Notes.Where(noteDto => noteDto.ObjectState == "delete").ToList();
deletedNotesDto.ForEach(noteDto =>
{
var note = new Note() { Id = noteDto.Id };
WriteContext.Notes.Attach(note);
WriteContext.Notes.Remove(note);
});
// add notes
var addedNotesDto = patientNoteDto.Notes.Where(noteDto => noteDto.ObjectState == "add").ToList();
addedNotesDto.ForEach(noteDto =>
{
var note = AutoMapper.Mapper.Map<Note>(noteDto);
patientNoteEnvelop.Notes.Add(note);
});
// update notes
var updatedNotesDto = patientNoteDto.Notes.Where(noteDto => noteDto.ObjectState == "update").ToList();
updatedNotesDto.ForEach(noteDto =>
{
var note = WriteContext.Notes.First(x => x.Id == noteDto.Id);
AutoMapper.Mapper.Map(noteDto, note);
});
if (!WriteContext.TrySaveChanges(ModelState)){
return BadRequest(ModelState);
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/PatientNotesApi
[ResponseType(typeof(PatientNoteDto))]
public IHttpActionResult PostPatientNote(PatientNoteDto patientNoteDto)
{
var isNewRecord = (patientNoteDto.Id == 0);
if (!isNewRecord)
{
return BadRequest("Only new patient can be created using PostPatientNote call");
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var patientNote = WriteContext.PatientNotes.Create();
AutoMapper.Mapper.Map(patientNoteDto, patientNote);
patientNote.RecordedDate = DateTime.Now;
WriteContext.PatientNotes.Add(patientNote);
if (!WriteContext.TrySaveChanges(ModelState))
{
return BadRequest(ModelState);
}
return CreatedAtRoute("DefaultApi", new { id = patientNoteDto.Id }, patientNoteDto);
}
// DELETE: api/PatientNotesApi/5
[ResponseType(typeof(PatientNote))]
public IHttpActionResult DeletePatientNote(int id)
{
PatientNote patientNote = WriteContext.PatientNotes.Include(x => x.Notes).FirstOrDefault(x => x.Id == id);
if (patientNote == null)
{
return NotFound();
}
for (int i = patientNote.Notes.Count-1; i >-1 ; i--)
{
WriteContext.Notes.Remove(patientNote.Notes.ElementAt(i));
}
WriteContext.PatientNotes.Remove(patientNote);
if (!WriteContext.TrySaveChanges(ModelState))
{
return BadRequest(ModelState);
}
return Ok(patientNote);
}
private bool PatientNoteExists(int id)
{
return ReadContext.PatientNotes.Count(e => e.Id == id) > 0;
}
}
} |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rays.Utility
{
/// <summary>
/// 海报图片帮助类
/// </summary>
public class ImageHelper
{
/// <summary>
/// 从网络地址获取图片
/// </summary>
/// <param name="url"></param>
public static Bitmap GetBitmapFromUrl(string url)
{
Bitmap img = null;
try
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] buf = wc.DownloadData(url);
MemoryStream ms = new MemoryStream(buf);
img = (Bitmap)System.Drawing.Bitmap.FromStream(ms); //img就是你要的Bitmap.
ms.Close();
wc.Dispose();
}
catch (Exception)
{
// ignored
}
return img;
}
#region C#图片处理 合并图片
/// <summary>
/// 调用此函数后使此两种图片合并,类似相册,有个
/// 背景图,中间贴自己的目标图片
/// </summary>
/// <param name="sourceImg">粘贴的源图片</param>
/// <param name="destImg">粘贴的目标图片</param>
/// 使用说明: string pic1Path = Server.MapPath(@"\testImg\wf.png");
/// 使用说明: string pic2Path = Server.MapPath(@"\testImg\yj.png");
/// 使用说明: System.Drawing.Image img = CombinImage(pic1Path, pic2Path);
/// 使用说明:img.Save(Server.MapPath(@"\testImg\Newwf.png"));
public static System.Drawing.Image CombinImage(string sourceImg, string destImg)
{
System.Drawing.Image imgBack = System.Drawing.Image.FromFile(sourceImg); //相框图片
System.Drawing.Image img = System.Drawing.Image.FromFile(destImg); //照片图片
//从指定的System.Drawing.Image创建新的System.Drawing.Graphics
Graphics g = Graphics.FromImage(imgBack);
g.DrawImage(imgBack, 0, 0, 148, 124); // g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
g.FillRectangle(System.Drawing.Brushes.Black, 16, 16, (int)112 + 2, ((int)73 + 2));//相片四周刷一层黑色边框
//g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
g.DrawImage(img, 17, 17, 112, 73);
GC.Collect();
return imgBack;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using InvoiceClient.Properties;
using Model.Schema.EIVO;
namespace InvoiceClient.Agent
{
public static class InvoiceCenterTransferManager
{
private static A1401Watcher _InvoiceWatcher;
private static B1401Watcher _AllowanceWatcher;
private static A0501Watcher _CancellationWatcher;
private static B0501Watcher _AllowanceCancellationWatcher;
private static A0401Watcher _A0401Watcher;
private static B0401Watcher _B0401Watcher;
public static void EnableAll(String fullPath)
{
_InvoiceWatcher = new A1401Watcher(Path.Combine(fullPath, Settings.Default.UploadA1401));
_InvoiceWatcher.StartUp();
_A0401Watcher = new A0401Watcher(Path.Combine(fullPath, Settings.Default.UploadA0401));
_A0401Watcher.StartUp();
_AllowanceWatcher = new B1401Watcher(Path.Combine(fullPath, Settings.Default.UploadB1401));
_AllowanceWatcher.StartUp();
_B0401Watcher = new B0401Watcher(Path.Combine(fullPath, Settings.Default.UploadB0401));
_B0401Watcher.StartUp();
_CancellationWatcher = new A0501Watcher(Path.Combine(fullPath, Settings.Default.UploadA0501));
_CancellationWatcher.StartUp();
_AllowanceCancellationWatcher = new B0501Watcher(Path.Combine(fullPath, Settings.Default.UploadB0501));
_AllowanceCancellationWatcher.StartUp();
}
public static void PauseAll()
{
if (_InvoiceWatcher != null)
{
_InvoiceWatcher.Dispose();
}
if (_A0401Watcher != null)
{
_A0401Watcher.Dispose();
}
if (_AllowanceWatcher != null)
{
_AllowanceWatcher.Dispose();
}
if (_B0401Watcher != null)
{
_B0401Watcher.Dispose();
}
if (_CancellationWatcher != null)
{
_CancellationWatcher.Dispose();
}
if (_AllowanceCancellationWatcher != null)
{
_AllowanceCancellationWatcher.Dispose();
}
}
public static String ReportError()
{
StringBuilder sb = new StringBuilder();
if (_InvoiceWatcher != null)
sb.Append(_InvoiceWatcher.ReportError());
if (_A0401Watcher != null)
sb.Append(_A0401Watcher.ReportError());
if (_CancellationWatcher != null)
sb.Append(_CancellationWatcher.ReportError());
if (_AllowanceWatcher != null)
sb.Append(_AllowanceWatcher.ReportError());
if (_B0401Watcher != null)
sb.Append(_B0401Watcher.ReportError());
if (_AllowanceCancellationWatcher != null)
sb.Append(_AllowanceCancellationWatcher.ReportError());
return sb.ToString();
}
public static void SetRetry()
{
_InvoiceWatcher.Retry();
_A0401Watcher.Retry();
_CancellationWatcher.Retry();
_AllowanceWatcher.Retry();
_B0401Watcher.Retry();
_AllowanceCancellationWatcher.Retry();
}
}
}
|
using System;
using System.Windows.Controls;
using System.Windows.Threading;
namespace Torshify.Radio.Spotify.Views.Settings
{
public partial class SpotifyLoginSectionView : UserControl
{
#region Fields
private DispatcherTimer _deferredLoginTimer;
#endregion Fields
#region Constructors
public SpotifyLoginSectionView()
{
InitializeComponent();
_deferredLoginTimer = new DispatcherTimer();
_deferredLoginTimer.Interval = TimeSpan.FromMilliseconds(750);
_deferredLoginTimer.Tick += DeferredLoginTimerOnTick;
}
#endregion Constructors
#region Properties
public SpotifyLoginSection Model
{
get
{
return DataContext as SpotifyLoginSection;
}
set
{
DataContext = value;
}
}
#endregion Properties
#region Methods
private void PasswordBoxPasswordChanged(object sender, System.Windows.RoutedEventArgs e)
{
_deferredLoginTimer.Stop();
_deferredLoginTimer.Start();
}
private void DeferredLoginTimerOnTick(object sender, EventArgs eventArgs)
{
_deferredLoginTimer.Stop();
Model.Login(_userName.Text, _password.Password);
}
#endregion Methods
}
} |
using OnlineExaminationSystem.Core.DataAccess;
using OnlineExaminationSystem.DataAccess.Abstract;
using OnlineExaminationSystem.DataAccess.Concrete.Context;
using OnlineExaminationSystem.Entities;
using OnlineExaminationSystem.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Text;
namespace OnlineExaminationSystem.DataAccess.Concrete
{
public class InstructorDal : EntityRepositoryBase<Instructor, OnlineExaminationSystemContext>, IInstructorDal
{
}
}
|
using BPiaoBao.Common.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBao.AppServices.DataContracts.DomesticTicket
{
public class OrderPayDto
{
/// <summary>
/// 支付流水号
/// </summary>
public string PaySerialNumber
{
get;
set;
}
/// <summary>
/// 代付流水号
/// </summary>
public string PaidSerialNumber
{
get;
set;
}
/// <summary>
/// 代付金额
/// </summary>
public decimal PaidMoney
{
get;
set;
}
/// <summary>
/// 支付金额
/// </summary>
public decimal PayMoney
{
get;
set;
}
/// <summary>
/// 具体支付方式代号
/// </summary>
public string PayMethodCode { get; set; }
/// <summary>
/// 支付方式
/// </summary>
public string PayMethod { get; set; }
/// <summary>
/// 代付方式
/// </summary>
public string PaidMethod { get; set; }
/// <summary>
/// 支付状态 0未支付 1已支付
/// </summary>
public EnumPayStatus PayStatus { get; set; }
/// <summary>
/// 代付状态 0未代付 1已代付
/// </summary>
public EnumPaidStatus PaidStatus { get; set; }
/// <summary>
/// 交易手续费
/// </summary>
public decimal TradePoundage
{
get;
set;
}
/// <summary>
/// 系统分润
/// </summary>
public decimal SystemFee
{
get;
set;
}
/// <summary>
/// 支付时间
/// </summary>
public DateTime? PayDateTime
{
get;
set;
}
/// <summary>
/// 代付时间
/// </summary>
public DateTime? PaidDateTime
{
get;
set;
}
public virtual List<PayBillDetailDto> PayBillDetailDtos
{
get;
set;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Yasl
{
public static class SerializerExtensions
{
public static void Write<T>(this ISerializationWriter writer, string name, T value)
{
writer.Write(typeof(T), name, value);
}
public static T Read<T>(this ISerializationReader reader, string name, bool allowCircularDependencies = false)
{
return (T)reader.Read(typeof(T), name, allowCircularDependencies);
}
public static IEnumerable<T> ReadSet<T>(this ISerializationReader reader, string itemName, bool allowCircularDependencies = false)
{
return reader.ReadSet(typeof(T), itemName, allowCircularDependencies).Cast<T>();
}
public static void WriteSet<T>(this ISerializationWriter writer, string itemName, IEnumerable set)
{
writer.WriteSet(typeof(T), itemName, set);
}
public static T ReadPrimitive<T>(this ISerializationReader reader)
{
return (T)reader.ReadPrimitive(typeof(T));
}
public static void WritePrimitive<T>(this ISerializationWriter writer, T value)
{
writer.WritePrimitive(typeof(T), value);
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System.Collections;
using System.Collections.Generic;
using DotNetNuke.Entities.Modules;
namespace DotNetNuke.Entities.Tabs
{
public interface ITabModulesController
{
/// <summary>
/// Returns an array of Modules well configured to be used into a Skin
/// </summary>
/// <param name="tab">TabInfo object</param>
ArrayList GetTabModules(TabInfo tab);
/// <summary>
/// Gets a collection of all setting values of <see cref="ModuleInfo"/> that contains the
/// setting name in its collection of settings.
/// </summary>
/// <param name="settingName">Name of the setting to look for</param>
Dictionary<int, string> GetTabModuleSettingsByName(string settingName);
/// <summary>
/// Gets a collection of all ID's of <see cref="ModuleInfo"/> that contains the setting name and
/// specific value in its collection of settings.
/// </summary>
/// <param name="settingName">Name of the setting to look for</param>
/// <param name="expectedValue">Value of the setting to look for</param>
IList<int> GetTabModuleIdsBySetting(string settingName, string expectedValue);
}
}
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Windows.Input;
using City_Center.Models;
using City_Center.Services;
using GalaSoft.MvvmLight.Command;
using Plugin.Share;
using Xamarin.Forms;
using static City_Center.Models.FavoritosResultado;
using City_Center.Clases;
using Plugin.Messaging;
using City_Center.Page;
using System.Linq;
using City_Center.PopUp;
namespace City_Center.ViewModels
{
public class FavoritoItemViewModel : FavoritoDetalle
{
#region Services
private ApiService apiService;
#endregion
#region Commands
public ICommand CompartirCommand
{
get
{
return new RelayCommand(CompartirUrl);
}
}
private async void CompartirUrl()
{
Plugin.Share.Abstractions.ShareMessage Compartir = new Plugin.Share.Abstractions.ShareMessage();
Compartir.Text = this.descripcion;
Compartir.Title = this.nombre;
if (this.gua_id_evento > 0)
{
Compartir.Url = "https://citycenter-rosario.com.ar/es/es/show-detail/" + this.gua_id_evento + "/" + this.nombre;
}
if (this.gua_id_promocion > 0)
{
Compartir.Url = "https://citycenter-rosario.com.ar/es/promocion-detail/" + this.gua_id_promocion + "/" + this.nombre;
}
if (this.gua_id_torneo > 0)
{
Compartir.Url = "https://citycenter-rosario.com.ar/es/casino/torneo-detail/" + this.gua_id_torneo + "/" + this.nombre;
}
if (this.gua_id_destacado > 0)
{
Compartir.Url = "https://citycenter-rosario.com.ar/es/promocion-detail/" + this.gua_id_destacado + "/" + this.nombre;
}
await CrossShare.Current.Share(Compartir);
}
public ICommand EliminaFavoritosCommand
{
get
{
return new RelayCommand(EliminaFavoritos);
}
}
private async void EliminaFavoritos()
{
try
{
bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn") ?
(bool)Application.Current.Properties["IsLoggedIn"] : false;
if (isLoggedIn)
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("gua_id",Convert.ToString(this.gua_id)),
});
var response = await this.apiService.Get<GuardadoGenerico>("/guardados", "/destroy", content);
if (!response.IsSuccess)
{
await Mensajes.Alerta("Ha habido un error en tu solicitud, por favor volvé a intentarlo");
return;
}
var list = (GuardadoGenerico)response.Result;
//var Item = MainViewModel.GetInstance().listFavoritos.resultado.Where(l => l.gua_id == this.gua_id).SingleOrDefault();
//var actualiza = MainViewModel.GetInstance().listFavoritos.resultado;//.Where(l => l.gua_id == this.gua_id).SingleOrDefault();
//actualiza.Remove(Item);
await Mensajes.Alerta("Eliminado con éxito");
}
else
{
await Mensajes.Alerta("Es necesario que te registres para completar esta acción");
}
}
catch (Exception)
{
await Mensajes.Alerta("Es necesario que te registres para completar esta acción");
}
}
public ICommand LlamarCommand
{
get
{
return new RelayCommand(Llamar);
}
}
private void Llamar()
{
var phoneCallTask = CrossMessaging.Current.PhoneDialer;
if (phoneCallTask.CanMakePhoneCall)
{
phoneCallTask.MakePhoneCall(this.telefono, this.nombre);
}
}
public ICommand CompraOnlineCommand
{
get
{
return new RelayCommand(CompraOnline);
}
}
private async void CompraOnline()
{
VariablesGlobales.RutaTiendaGuardados = link;
await((MasterPage)Application.Current.MainPage).Detail.Navigation.PushAsync(new WebViewTienda2());
}
public ICommand InscribirteTorneoCommand
{
get
{
return new RelayCommand(Inscribir);
}
}
private async void Inscribir()
{
//MainViewModel.GetInstance().TorneoDetalle = new TorneoDetalleViewModel();
await((MasterPage)Application.Current.MainPage).Detail.Navigation.PushAsync(new TorneoInscripcion());
}
#endregion
#region Contructors
public FavoritoItemViewModel()
{
this.apiService = new ApiService();
}
#endregion
}
}
|
using System;
using System.Text;
class MainClass
{
public static void Main ()
{
Console.WriteLine ("Enter integer a number:");
long integer = long.Parse (Console.ReadLine ());
StringBuilder text = new StringBuilder ();
StringBuilder tempText = new StringBuilder ();
while (integer != 0 || integer < 0) {
if (integer % 2 == 0)
text.Append ('0');
else
text.Append ('1');
integer /= 2;
}
//reverse
for (int i = 1; i <= text.Length; i++) {
tempText.Append( text [text.Length - i]);
}
Console.WriteLine (tempText);
}
} |
namespace WikiMusic.Services.Controllers
{
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
using AutoMapper.QueryableExtensions;
using Data;
using Models;
using WebGrease.Css.Extensions;
using WikiMusic.Models;
[EnableCors(origins: "*", headers: "*", methods: "*")]
[RoutePrefix("api/albums")]
public class AlbumsController : ApiController
{
private IWikiMusicData data;
public AlbumsController()
{
this.data = new WikiMusicData();
}
public IHttpActionResult Get()
{
var albums = this.data.Albums.All().ToList();
return this.Ok(albums);
}
public IHttpActionResult GetById(int id)
{
return this.Ok(this.data.Albums.SearchFor(x => x.ID == id).First());
}
public IHttpActionResult Post([FromBody] IEnumerable<AlbumRequestModel> albums)
{
albums
.ForEach(album =>
{
var newAlbum = new Album
{
Title = album.Title,
Year = album.Year,
Producer = album.Producer,
Artists = album.Artists.AsQueryable().ProjectTo<Artist>().ToList(),
ImgLink = album.ImgLink
};
this.data.Albums.Add(newAlbum);
});
this.data.SaveChanges();
return this.Ok();
}
public IHttpActionResult Put(UpdateAlbumSongs data)
{
this.data.Albums.SearchFor(x => x.ID == data.Id)
.ForEach(a =>
{
data.Songs.AsQueryable().ProjectTo<Song>().ForEach(s => a.Songs.Add(s));
});
this.data.SaveChanges();
return this.Ok();
}
public IHttpActionResult Put(int id, [FromBody] AlbumRequestModel updates)
{
var album = this.data.Albums.SearchFor(x => x.ID == id).First();
updates
.GetType()
.GetProperties()
.Where(x => x.GetValue(updates) != null)
.ToList()
.ForEach(pr =>
{
album.GetType().GetProperty(pr.Name).SetValue(album, pr.GetValue(updates));
});
this.data.Albums.Update(album);
this.data.SaveChanges();
return this.Ok();
}
public IHttpActionResult Delete([FromBody] int id)
{
var album = this.data.Albums.SearchFor(x => x.ID == id).FirstOrDefault();
this.data.Albums.Delete(album);
this.data.SaveChanges();
return this.Ok();
}
}
} |
using NTShop.Data.Infrastructure;
using NTShop.Data.Reponsitories;
using NTShop.Model.Models;
namespace NTShop.Service
{
public interface IFeedbackService
{
Feedback Create(Feedback feedback);
void Save();
}
public class FeedbackService:IFeedbackService
{
public IFeedbackRepository _feedbackRepository;
public IUnitOfWork _unitOfWork;
public FeedbackService(IFeedbackRepository feedbackRepository, IUnitOfWork unitOfWork)
{
this._feedbackRepository = feedbackRepository;
this._unitOfWork = unitOfWork;
}
public Feedback Create(Feedback feedback)
{
return _feedbackRepository.Add(feedback);
}
public void Save()
{
_unitOfWork.Commit();
}
}
} |
using Umbraco.Core;
namespace AgeBaseTemplate.Core.Wrappers
{
public interface IProfileLogger
{
DisposableTimer TraceDuration<T>(string startMessage);
}
} |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Xml;
namespace ServerHost
{
/// <summary>
/// An operation behavior that replaces the default WCF serializer with the <see cref="LoggingSerializer" />.
/// </summary>
public class SerializationLoggingOperationBehavior : DataContractSerializerOperationBehavior
{
/// <summary>
/// Initializes a new instance of the <see cref="SerializationLoggingOperationBehavior" /> class.
/// </summary>
/// <param name="operation">The operation being examined.</param>
public SerializationLoggingOperationBehavior(OperationDescription operation)
: base(operation)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SerializationLoggingOperationBehavior" /> class.
/// </summary>
/// <param name="operation">The operation being examined.</param>
/// <param name="dataContractFormatAttribute">
/// The run-time object that exposes customization properties for the operation described by <paramref name="operation" />.
/// </param>
public SerializationLoggingOperationBehavior(
OperationDescription operation,
DataContractFormatAttribute dataContractFormatAttribute)
: base(operation, dataContractFormatAttribute)
{
}
/// <summary>
/// Creates an XML serializer for the specified type.
/// </summary>
/// <param name="type">The type to serialize or deserialize.</param>
/// <param name="name">The name of the serialized type.</param>
/// <param name="ns">The namespace of the serialized type.</param>
/// <param name="knownTypes">The collection of known types.</param>
/// <returns>
/// The XML serializer for the specified type.
/// </returns>
public override XmlObjectSerializer CreateSerializer(
Type type,
XmlDictionaryString name,
XmlDictionaryString ns,
IList<Type> knownTypes)
{
return new LoggingSerializer(
type,
name,
ns,
knownTypes,
this.MaxItemsInObjectGraph,
this.IgnoreExtensionDataObject,
false,
this.DataContractSurrogate,
this.DataContractResolver);
}
/// <summary>
/// Creates an XML serializer for the specified type.
/// </summary>
/// <param name="type">The type to serialize or deserialize.</param>
/// <param name="name">The name of the serialized type.</param>
/// <param name="ns">The namespace of the serialized type.</param>
/// <param name="knownTypes">The collection of known types.</param>
/// <returns>
/// The XML serializer for the specified type.
/// </returns>
public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
{
return new LoggingSerializer(
type,
name,
ns,
knownTypes,
this.MaxItemsInObjectGraph,
this.IgnoreExtensionDataObject,
false,
this.DataContractSurrogate,
this.DataContractResolver);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.AddIn.Contract;
namespace Tivo.Has.Contracts
{
public interface IHasApplicationConfiguratorContract : IContract
{
string Name { get; set; }
// list accessable assemblies - this is base directory and all directories in relative search path
IListContract<string> GetAccessableAssemblies();
// list applications in an assembly - return assembly qualified type name
IListContract<string> GetApplications(string assemblyPath);
// allow adding application identities (both free form key in and find and select)
//void AddApplication(string name, Uri endPoint, string assemblyQualifiedTypeName);
// a list api works better for adding and removing applications as well as listing existing applications
IListContract<HasApplicationConfiguration> ApplicationConfigurations { get; }
void CommitChanges();
void RollbackChanges();
// TODO: do we need start and stop control here or just in the main app?
}
[Serializable]
public struct HasApplicationConfiguration
{
public HasApplicationConfiguration(string name, Uri endPoint, string assemblyQualifiedTypeName)
: this()
{
Name = name;
EndPoint = endPoint;
AssemblyQualifiedTypeName = assemblyQualifiedTypeName;
}
public string Name { get; set; }
public Uri EndPoint { get; set; }
public string AssemblyQualifiedTypeName { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Net;
using System.Linq;
using System.IO;
using System.Text;
namespace SpeedHackDetector.Network
{
public class IpStorage
{
private ConcurrentDictionary<IPAddress, List<String>> m_Ip2Account;
public IpStorage()
{
this.m_Ip2Account = new ConcurrentDictionary<IPAddress, List<String>>();
System.Timers.Timer m_Timer = new System.Timers.Timer();
m_Timer.Elapsed += new System.Timers.ElapsedEventHandler(checkAccount);
m_Timer.Interval = 1000;
m_Timer.Enabled = true;
m_Timer.AutoReset = true;
}
private void checkAccount(object sender, System.Timers.ElapsedEventArgs e)
{
foreach(IPAddress key in this.m_Ip2Account.Keys)
{
List<String> acc = this.m_Ip2Account[key];
if (acc.Count > 1)
{
Warning(acc,key);
}
}
}
public void Add(String username, IPAddress addr)
{
Log(username, addr);
List<String> accounts = null;
if (!m_Ip2Account.ContainsKey(addr))
{
accounts = new List<String>();
}
else
{
accounts = m_Ip2Account[addr];
}
accounts.Add(username);
this.m_Ip2Account.TryAdd(addr, accounts);
}
public void remove(IPAddress addr)
{
List<String> accounts = new List<String>();
this.m_Ip2Account.TryRemove(addr, out accounts);
}
public void Warning(List<String> usernames, IPAddress addr)
{
String baseDirecotry = Directory.GetCurrentDirectory();
AppendPath(ref baseDirecotry, "Logs");
AppendPath(ref baseDirecotry, "IpLogs");
String doppi = Path.Combine(baseDirecotry, "sospettidoppi.log");
String accounts = getUsernameFromList(usernames);
using (StreamWriter sw = new StreamWriter(doppi, true))
sw.WriteLine("Accounts: " + accounts + " ha loggato con ip " + addr.ToString() + " in Data: " + DateTime.Now);
}
private string getUsernameFromList(IEnumerable<String> usernames)
{
String result = "";
foreach (String username in usernames)
{
result += username +",";
}
return result;
}
public void Log(String username, IPAddress addr)
{
String baseDirecotry = Directory.GetCurrentDirectory();
AppendPath(ref baseDirecotry, "Logs");
AppendPath(ref baseDirecotry, "IpLogs");
String generalLog = Path.Combine(baseDirecotry, "ip.log");
String userLog = Path.Combine(baseDirecotry, String.Format("{0}.log", username));
using (StreamWriter sw = new StreamWriter(generalLog, true))
sw.WriteLine("Account: " + username + " ha loggato con ip " + addr.ToString() + " in Data: " + DateTime.Now);
using (StreamWriter sw = new StreamWriter(userLog, true))
sw.WriteLine("Account: " + username + " ha loggato con ip " + addr.ToString() + " in Data: " + DateTime.Now);
}
private void AppendPath(ref string path, string toAppend)
{
path = Path.Combine(path, toAppend);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using Random = UnityEngine.Random;
public class BallSpawner : MonoBehaviour
{
[SerializeField] Vector2 spawnLocationMin;
[SerializeField] Vector2 spawnLocationMax;
[SerializeField] private GameObject prefabBall;
private Timer ballSpawnTimer;
public static int ballCounter = 0;
private HudReduceBallsLeft reduceBallsLeft=new HudReduceBallsLeft();
void Start()
{
EventManager.AddReduceBallsLEftInvoker(this);
EventManager.AddReduceBallsLEftListener(HUDManager._instance.ReduceBallsLeft);
ballSpawnTimer = gameObject.AddComponent<Timer>();
ballSpawnTimer.AddTimerFinishedListener(ResetTimer);
InitializeBallSpawn();
ResetTimer();
}
void Update()
{
if(ballCounter < 1)
{
SpawnBall();
}
}
void ResetTimer()
{
SpawnBall();
ballSpawnTimer.Duration=Random.Range(ConfigurationUtils.MinBallSpawnTime, ConfigurationUtils.MaxBallSpawnTime+1);
ballSpawnTimer.Run();
print("Reseting timer");
}
void SpawnBall()
{
// make sure we don't spawn into a collision
Instantiate(prefabBall);
AudioManager.Play(AudioClipName.Spawn);
ballCounter++;
// HUDManager._instance.ReduceBallsLeft();
reduceBallsLeft.Invoke();
HUDManager._instance.SetBallNumber(ballCounter);
}
void InitializeBallSpawn()
{
GameObject tempBall = Instantiate<GameObject>(prefabBall);
float ballColliderHalfWidth = 0;
float ballColliderHalfHeight = 0;
if (tempBall.GetComponent<BoxCollider2D>() != null)
{
BoxCollider2D collider = tempBall.GetComponent<BoxCollider2D>();
ballColliderHalfWidth = collider.size.x / 2;
ballColliderHalfHeight = collider.size.y / 2;
}
else
{
CircleCollider2D collider = tempBall.GetComponent<CircleCollider2D>();
ballColliderHalfWidth = collider.radius;
ballColliderHalfHeight = collider.radius;
}
spawnLocationMin = new Vector2(
tempBall.transform.position.x - ballColliderHalfWidth,
tempBall.transform.position.y - ballColliderHalfHeight);
spawnLocationMax = new Vector2(
tempBall.transform.position.x + ballColliderHalfWidth,
tempBall.transform.position.y + ballColliderHalfHeight);
Destroy(tempBall);
}
public void AddReduceBallsLeftListener(UnityAction handler)
{
reduceBallsLeft.AddListener(handler);
}
private void OnDrawGizmos()
{
Gizmos.color=new Color(1,0,0,.5f);
Gizmos.DrawLine(spawnLocationMin,new Vector3(spawnLocationMax.x,spawnLocationMin.y));
Gizmos.DrawLine(new Vector3(spawnLocationMax.x,spawnLocationMin.y),spawnLocationMax);
Gizmos.DrawLine(new Vector3(spawnLocationMin.x,spawnLocationMax.y),spawnLocationMax);
Gizmos.DrawLine(new Vector3(spawnLocationMin.x,spawnLocationMax.y),spawnLocationMin);
}
}
|
namespace Factory.Library.Ingredients.Veggies
{
public class Spinach:IVeggie
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fleetmatics
{
class Rabbits
{
internal static List<RabbitPair> rabbits = new List<RabbitPair>();
public static int RabbitCount(int month)
{
//add magically appeared pair of rabbits
if (month >= 0)
{
rabbits.Add(new RabbitPair());
}
for (int m = 1; m <= month; m++)
{
IEnumerator<RabbitPair> itr = rabbits.GetEnumerator();
int newPairs = 0;
while (itr.MoveNext())
{
RabbitPair rp = itr.Current;
rp.increaseAgeByAMonth();
if (rp.Mature)
{
//Rabbit pair is mature to give birth to babies
newPairs++;
}
}
for (int i = 0; i < newPairs; i++)
{
rabbits.Add(new RabbitPair());
}
}
return rabbits.Count;
}
public static void Main(string[] args)
{
Console.WriteLine(RabbitCount(12));
Console.Read();
}
}
internal class RabbitPair
{
internal int age = 0;
public virtual void increaseAgeByAMonth()
{
age++;
}
public virtual int Age
{
set
{
this.age = value;
}
get
{
return age;
}
}
public virtual bool Mature
{
get
{
return (age >= 3) ? true : false;
}
}
}
}
|
using System;
namespace RefactoringApp.OrganizingData.Replace_type_code_with_subclasses
{
// You have an immutable type code that affects the behavior of a class.
public enum TypeCar
{
Fiat = 0,
Bmw = 1,
Honda = 2
}
public class Car
{
private TypeCar _type;
public Car(TypeCar type)
{
_type = type;
}
public virtual TypeCar GetType()
{
return _type;
}
}
public abstract class CarRefactoring
{
private TypeCar _type;
protected CarRefactoring(TypeCar type)
{
_type = type;
}
public static CarRefactoring Create(TypeCar type)
{
try
{
return (CarRefactoring)Activator.CreateInstance(Type.GetType($"RefactoringApp.OrganizingData.Replace_type_code_with_subclasses.{type}"), new object[] { type });
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
public abstract TypeCar GetType();
}
public class Fiat : CarRefactoring
{
private Fiat(TypeCar type) : base(type)
{
}
public override TypeCar GetType()
{
return TypeCar.Fiat;
}
}
public class Bmw : CarRefactoring
{
private Bmw(TypeCar type) : base(type)
{
}
public override TypeCar GetType()
{
return TypeCar.Bmw;
}
}
public class Honda : CarRefactoring
{
private Honda(TypeCar type) : base(type)
{
}
public override TypeCar GetType()
{
return TypeCar.Honda;
}
}
public class Run
{
void Main()
{
Console.WriteLine(CarRefactoring.Create(TypeCar.Fiat).GetType());
Console.WriteLine(CarRefactoring.Create(TypeCar.Bmw).GetType());
Console.WriteLine(CarRefactoring.Create(TypeCar.Honda).GetType());
}
}
}
|
namespace HH.RulesEngine.Data.Enums
{
public enum RuleAssignedTo
{
OrderTotal = 1,
Products = 2,
Shipping = 3,
SubTotal = 4,
CardTransactions = 5
}
} |
/**
*┌──────────────────────────────────────────────────────────────┐
*│ 描 述:
*│ 作 者:lw
*│ 版 本:1.0 模板代码自动生成
*│ 创建时间:2019-05-23 16:43:42
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│ 命名空间: EWF.Services
*│ 类 名: SYS_DEPARTMENTService
*└──────────────────────────────────────────────────────────────┘
*/
using EWF.Entity;
using EWF.IRepository.SysManage;
using EWF.IServices;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using EWF.Util;
using EWF.Util.Page;
namespace EWF.Services
{
public class SYS_DEPARTMENTService: ISYS_DEPARTMENTService
{
private readonly ISYS_DEPARTMENTRepository repository;
public SYS_DEPARTMENTService(ISYS_DEPARTMENTRepository _repository)
{
repository = _repository;
}
public Page<SYS_DEPARTMENT> GetDepartmentData(int pageIndex, int pageSize, string DCode, string DName)
{
return repository.GetDepartmentData(pageIndex, pageSize, DCode, DName);
}
/// <summary>
/// 获取部门分页数据
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="DCode"></param>
/// <param name="DName"></param>
/// <param name="UName"></param>
/// <returns></returns>
public Page<dynamic> GetDepartmentData(int pageIndex, int pageSize, string DCode, string DName, string UName, string UnitId)
{
return repository.GetDepartmentData(pageIndex, pageSize, DCode, DName,UName, UnitId);
}
public string Insert(SYS_DEPARTMENT entity)
{
var result = repository.Insert<string>(entity);
if (!result.IsEmpty())
{
return "录入成功";
}
return "录入失败";
}
public string Update(SYS_DEPARTMENT entity)
{
var result = repository.Update(entity);
if (result)
{
return "编辑成功";
}
return "编辑失败";
}
public string Delete(string ID)
{
var result = repository.Delete(ID);
if (result > 0)
{
return "删除成功";
}
return "删除失败";
}
public SYS_DEPARTMENT GetUnitByID(string ID)
{
var result = repository.Get(ID);
return result;
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Generic.V40;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using Validation;
namespace System.Collections.Immutable
{
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableDictionary<,>.DebuggerProxy))]
public sealed class ImmutableDictionary<TKey, TValue> : IImmutableDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IImmutableDictionaryInternal<TKey, TValue>, IHashKeyCollection<TKey>, IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
{
public readonly static ImmutableDictionary<TKey, TValue> Empty;
private readonly static Action<KeyValuePair<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>> FreezeBucketAction;
private readonly Int32 count;
private readonly ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root;
private readonly ImmutableDictionary<TKey, TValue>.Comparers comparers;
public Int32 Count
{
get
{
return this.count;
}
}
public Boolean IsEmpty
{
get
{
return this.Count == 0;
}
}
public TValue this[TKey key]
{
get
{
TValue tValue;
Requires.NotNullAllowStructs<TKey>(key, "key");
if (!this.TryGetValue(key, out tValue))
{
throw new KeyNotFoundException();
}
return tValue;
}
}
public IEqualityComparer<TKey> KeyComparer
{
get
{
return this.comparers.KeyComparer;
}
}
public IEnumerable<TKey> Keys
{
get
{
foreach (KeyValuePair<Int32, ImmutableDictionary<TKey, TValue>.HashBucket> keyValuePair in this.root)
{
foreach (KeyValuePair<TKey, TValue> value in keyValuePair.Value)
{
yield return value.Key;
}
}
}
}
private ImmutableDictionary<TKey, TValue>.MutationInput Origin
{
get
{
return new ImmutableDictionary<TKey, TValue>.MutationInput(this);
}
}
Boolean System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly
{
get
{
return true;
}
}
TValue System.Collections.Generic.IDictionary<TKey, TValue>.this[TKey key]
{
get
{
return this[key];
}
set
{
throw new NotSupportedException();
}
}
ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys
{
get
{
return new KeysCollectionAccessor<TKey, TValue>(this);
}
}
ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values
{
get
{
return new ValuesCollectionAccessor<TKey, TValue>(this);
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
Boolean System.Collections.ICollection.IsSynchronized
{
get
{
return true;
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
Object System.Collections.ICollection.SyncRoot
{
get
{
return this;
}
}
Boolean System.Collections.IDictionary.IsFixedSize
{
get
{
return true;
}
}
Boolean System.Collections.IDictionary.IsReadOnly
{
get
{
return true;
}
}
Object System.Collections.IDictionary.this[Object key]
{
get
{
return this[(TKey)key];
}
set
{
throw new NotSupportedException();
}
}
ICollection System.Collections.IDictionary.Keys
{
get
{
return new KeysCollectionAccessor<TKey, TValue>(this);
}
}
ICollection System.Collections.IDictionary.Values
{
get
{
return new ValuesCollectionAccessor<TKey, TValue>(this);
}
}
public IEqualityComparer<TValue> ValueComparer
{
get
{
return this.comparers.ValueComparer;
}
}
public IEnumerable<TValue> Values
{
get
{
foreach (KeyValuePair<Int32, ImmutableDictionary<TKey, TValue>.HashBucket> keyValuePair in this.root)
{
foreach (KeyValuePair<TKey, TValue> value in keyValuePair.Value)
{
yield return value.Value;
}
}
}
}
static ImmutableDictionary()
{
ImmutableDictionary<TKey, TValue>.Empty = new ImmutableDictionary<TKey, TValue>(null);
ImmutableDictionary<TKey, TValue>.FreezeBucketAction = (KeyValuePair<Int32, ImmutableDictionary<TKey, TValue>.HashBucket> kv) => kv.Value.Freeze();
}
private ImmutableDictionary(ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root, ImmutableDictionary<TKey, TValue>.Comparers comparers, Int32 count)
: this(Requires.NotNull<ImmutableDictionary<TKey, TValue>.Comparers>(comparers, "comparers"))
{
Requires.NotNull<ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node>(root, "root");
root.Freeze(ImmutableDictionary<TKey, TValue>.FreezeBucketAction);
this.root = root;
this.count = count;
}
private ImmutableDictionary(ImmutableDictionary<TKey, TValue>.Comparers comparers = null)
{
this.comparers = comparers ?? ImmutableDictionary<TKey, TValue>.Comparers.Get(EqualityComparer<TKey>.Default, EqualityComparer<TValue>.Default);
this.root = ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node.EmptyNode;
}
public ImmutableDictionary<TKey, TValue> Add(TKey key, TValue value)
{
Requires.NotNullAllowStructs<TKey>(key, "key");
ImmutableDictionary<TKey, TValue>.MutationResult mutationResult = ImmutableDictionary<TKey, TValue>.Add(key, value, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.ThrowIfValueDifferent, new ImmutableDictionary<TKey, TValue>.MutationInput(this));
return mutationResult.Finalize(this);
}
private static ImmutableDictionary<TKey, TValue>.MutationResult Add(TKey key, TValue value, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior behavior, ImmutableDictionary<TKey, TValue>.MutationInput origin)
{
ImmutableDictionary<TKey, TValue>.OperationResult operationResult;
Requires.NotNullAllowStructs<TKey>(key, "key");
Int32 hashCode = origin.KeyComparer.GetHashCode(key);
ImmutableDictionary<TKey, TValue>.HashBucket valueOrDefault = origin.Root.GetValueOrDefault(hashCode, Comparer<Int32>.Default);
ImmutableDictionary<TKey, TValue>.HashBucket tKeys = valueOrDefault.Add(key, value, origin.KeyOnlyComparer, origin.ValueComparer, behavior, out operationResult);
if (operationResult == ImmutableDictionary<TKey, TValue>.OperationResult.NoChangeRequired)
{
return new ImmutableDictionary<TKey, TValue>.MutationResult(origin);
}
ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node nums = ImmutableDictionary<TKey, TValue>.UpdateRoot(origin.Root, hashCode, tKeys, origin.HashBucketComparer);
return new ImmutableDictionary<TKey, TValue>.MutationResult(nums, (operationResult == ImmutableDictionary<TKey, TValue>.OperationResult.SizeChanged ? 1 : 0));
}
public ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
Requires.NotNull<IEnumerable<KeyValuePair<TKey, TValue>>>(pairs, "pairs");
return this.AddRange(pairs, false);
}
private static ImmutableDictionary<TKey, TValue>.MutationResult AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items, ImmutableDictionary<TKey, TValue>.MutationInput origin, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior collisionBehavior = (ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior)2)
{
ImmutableDictionary<TKey, TValue>.OperationResult operationResult;
Requires.NotNull<IEnumerable<KeyValuePair<TKey, TValue>>>(items, "items");
Int32 num = 0;
ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root = origin.Root;
foreach (KeyValuePair<TKey, TValue> item in items)
{
Int32 hashCode = origin.KeyComparer.GetHashCode(item.Key);
ImmutableDictionary<TKey, TValue>.HashBucket valueOrDefault = root.GetValueOrDefault(hashCode, Comparer<Int32>.Default);
ImmutableDictionary<TKey, TValue>.HashBucket tKeys = valueOrDefault.Add(item.Key, item.Value, origin.KeyOnlyComparer, origin.ValueComparer, collisionBehavior, out operationResult);
root = ImmutableDictionary<TKey, TValue>.UpdateRoot(root, hashCode, tKeys, origin.HashBucketComparer);
if (operationResult != ImmutableDictionary<TKey, TValue>.OperationResult.SizeChanged)
{
continue;
}
num++;
}
return new ImmutableDictionary<TKey, TValue>.MutationResult(root, num);
}
private ImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, Boolean avoidToHashMap)
{
ImmutableDictionary<TKey, TValue> tKeys;
Requires.NotNull<IEnumerable<KeyValuePair<TKey, TValue>>>(pairs, "pairs");
if (this.IsEmpty && !avoidToHashMap && ImmutableDictionary<TKey, TValue>.TryCastToImmutableMap(pairs, out tKeys))
{
return tKeys.WithComparers(this.KeyComparer, this.ValueComparer);
}
ImmutableDictionary<TKey, TValue>.MutationResult mutationResult = ImmutableDictionary<TKey, TValue>.AddRange(pairs, this.Origin, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.ThrowIfValueDifferent);
return mutationResult.Finalize(this);
}
public ImmutableDictionary<TKey, TValue> Clear()
{
if (this.IsEmpty)
{
return this;
}
return ImmutableDictionary<TKey, TValue>.EmptyWithComparers(this.comparers);
}
public Boolean Contains(KeyValuePair<TKey, TValue> pair)
{
return ImmutableDictionary<TKey, TValue>.Contains(pair, this.Origin);
}
private static Boolean Contains(KeyValuePair<TKey, TValue> keyValuePair, ImmutableDictionary<TKey, TValue>.MutationInput origin)
{
ImmutableDictionary<TKey, TValue>.HashBucket tKeys;
TValue tValue;
Int32 hashCode = origin.KeyComparer.GetHashCode(keyValuePair.Key);
if (!origin.Root.TryGetValue(hashCode, Comparer<Int32>.Default, out tKeys))
{
return false;
}
if (!tKeys.TryGetValue(keyValuePair.Key, origin.KeyOnlyComparer, out tValue))
{
return false;
}
return origin.ValueComparer.Equals(tValue, keyValuePair.Value);
}
public Boolean ContainsKey(TKey key)
{
Requires.NotNullAllowStructs<TKey>(key, "key");
return ImmutableDictionary<TKey, TValue>.ContainsKey(key, new ImmutableDictionary<TKey, TValue>.MutationInput(this));
}
private static Boolean ContainsKey(TKey key, ImmutableDictionary<TKey, TValue>.MutationInput origin)
{
ImmutableDictionary<TKey, TValue>.HashBucket tKeys;
TValue tValue;
Int32 hashCode = origin.KeyComparer.GetHashCode(key);
if (!origin.Root.TryGetValue(hashCode, Comparer<Int32>.Default, out tKeys))
{
return false;
}
return tKeys.TryGetValue(key, origin.KeyOnlyComparer, out tValue);
}
public Boolean ContainsValue(TValue value)
{
return this.Values.Contains<TValue>(value, this.ValueComparer);
}
private static ImmutableDictionary<TKey, TValue> EmptyWithComparers(ImmutableDictionary<TKey, TValue>.Comparers comparers)
{
Requires.NotNull<ImmutableDictionary<TKey, TValue>.Comparers>(comparers, "comparers");
if (ImmutableDictionary<TKey, TValue>.Empty.comparers == comparers)
{
return ImmutableDictionary<TKey, TValue>.Empty;
}
return new ImmutableDictionary<TKey, TValue>(comparers);
}
public ImmutableDictionary<TKey, TValue>.Enumerator GetEnumerator()
{
return new ImmutableDictionary<TKey, TValue>.Enumerator(this.root, null);
}
public ImmutableDictionary<TKey, TValue> Remove(TKey key)
{
Requires.NotNullAllowStructs<TKey>(key, "key");
ImmutableDictionary<TKey, TValue>.MutationResult mutationResult = ImmutableDictionary<TKey, TValue>.Remove(key, new ImmutableDictionary<TKey, TValue>.MutationInput(this));
return mutationResult.Finalize(this);
}
private static ImmutableDictionary<TKey, TValue>.MutationResult Remove(TKey key, ImmutableDictionary<TKey, TValue>.MutationInput origin)
{
ImmutableDictionary<TKey, TValue>.HashBucket tKeys;
ImmutableDictionary<TKey, TValue>.OperationResult operationResult;
Int32 hashCode = origin.KeyComparer.GetHashCode(key);
if (!origin.Root.TryGetValue(hashCode, Comparer<Int32>.Default, out tKeys))
{
return new ImmutableDictionary<TKey, TValue>.MutationResult(origin);
}
ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node nums = ImmutableDictionary<TKey, TValue>.UpdateRoot(origin.Root, hashCode, tKeys.Remove(key, origin.KeyOnlyComparer, out operationResult), origin.HashBucketComparer);
return new ImmutableDictionary<TKey, TValue>.MutationResult(nums, (operationResult == ImmutableDictionary<TKey, TValue>.OperationResult.SizeChanged ? -1 : 0));
}
public ImmutableDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys)
{
ImmutableDictionary<TKey, TValue>.HashBucket tKeys;
ImmutableDictionary<TKey, TValue>.OperationResult operationResult;
Requires.NotNull<IEnumerable<TKey>>(keys, "keys");
Int32 num = this.count;
ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node nums = this.root;
foreach (TKey key in keys)
{
Int32 hashCode = this.KeyComparer.GetHashCode(key);
if (!nums.TryGetValue(hashCode, Comparer<Int32>.Default, out tKeys))
{
continue;
}
ImmutableDictionary<TKey, TValue>.HashBucket tKeys1 = tKeys.Remove(key, this.comparers.KeyOnlyComparer, out operationResult);
nums = ImmutableDictionary<TKey, TValue>.UpdateRoot(nums, hashCode, tKeys1, this.comparers.HashBucketEqualityComparer);
if (operationResult != ImmutableDictionary<TKey, TValue>.OperationResult.SizeChanged)
{
continue;
}
num--;
}
return this.Wrap(nums, num);
}
public ImmutableDictionary<TKey, TValue> SetItem(TKey key, TValue value)
{
Requires.NotNullAllowStructs<TKey>(key, "key");
ImmutableDictionary<TKey, TValue>.MutationResult mutationResult = ImmutableDictionary<TKey, TValue>.Add(key, value, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.SetValue, new ImmutableDictionary<TKey, TValue>.MutationInput(this));
return mutationResult.Finalize(this);
}
public ImmutableDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull<IEnumerable<KeyValuePair<TKey, TValue>>>(items, "items");
ImmutableDictionary<TKey, TValue>.MutationResult mutationResult = ImmutableDictionary<TKey, TValue>.AddRange(items, this.Origin, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.SetValue);
return mutationResult.Finalize(this);
}
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException();
}
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, Int32 arrayIndex)
{
Requires.NotNull<KeyValuePair<TKey, TValue>[]>(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex", null);
Requires.Range((Int32)array.Length >= arrayIndex + this.Count, "arrayIndex", null);
foreach (KeyValuePair<TKey, TValue> keyValuePair in this)
{
Int32 num = arrayIndex;
arrayIndex = num + 1;
array[num] = keyValuePair;
}
}
Boolean System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException();
}
void System.Collections.Generic.IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
throw new NotSupportedException();
}
Boolean System.Collections.Generic.IDictionary<TKey, TValue>.Remove(TKey key)
{
throw new NotSupportedException();
}
IEnumerator<KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
void System.Collections.ICollection.CopyTo(Array array, Int32 arrayIndex)
{
Requires.NotNull<Array>(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex", null);
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex", null);
foreach (KeyValuePair<TKey, TValue> keyValuePair in this)
{
Object dictionaryEntry = new DictionaryEntry((Object)keyValuePair.Key, (Object)keyValuePair.Value);
Int32[] numArray = new Int32[1];
Int32 num = arrayIndex;
arrayIndex = num + 1;
numArray[0] = num;
array.SetValue(dictionaryEntry, numArray);
}
}
void System.Collections.IDictionary.Add(Object key, Object value)
{
throw new NotSupportedException();
}
void System.Collections.IDictionary.Clear()
{
throw new NotSupportedException();
}
Boolean System.Collections.IDictionary.Contains(Object key)
{
return this.ContainsKey((TKey)key);
}
IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
void System.Collections.IDictionary.Remove(Object key)
{
throw new NotSupportedException();
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
IImmutableDictionary<TKey, TValue> System.Collections.Immutable.IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
return this.Add(key, value);
}
IImmutableDictionary<TKey, TValue> System.Collections.Immutable.IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs)
{
return this.AddRange(pairs);
}
IImmutableDictionary<TKey, TValue> System.Collections.Immutable.IImmutableDictionary<TKey, TValue>.Clear()
{
return this.Clear();
}
IImmutableDictionary<TKey, TValue> System.Collections.Immutable.IImmutableDictionary<TKey, TValue>.Remove(TKey key)
{
return this.Remove(key);
}
IImmutableDictionary<TKey, TValue> System.Collections.Immutable.IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys)
{
return this.RemoveRange(keys);
}
IImmutableDictionary<TKey, TValue> System.Collections.Immutable.IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value)
{
return this.SetItem(key, value);
}
IImmutableDictionary<TKey, TValue> System.Collections.Immutable.IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
return this.SetItems(items);
}
public ImmutableDictionary<TKey, TValue>.Builder ToBuilder()
{
return new ImmutableDictionary<TKey, TValue>.Builder(this);
}
private static Boolean TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, out ImmutableDictionary<TKey, TValue> other)
{
other = sequence as ImmutableDictionary<TKey, TValue>;
if (other != null)
{
return true;
}
ImmutableDictionary<TKey, TValue>.Builder tKeys = sequence as ImmutableDictionary<TKey, TValue>.Builder;
if (tKeys == null)
{
return false;
}
other = tKeys.ToImmutable();
return true;
}
public Boolean TryGetKey(TKey equalKey, out TKey actualKey)
{
Requires.NotNullAllowStructs<TKey>(equalKey, "equalKey");
return ImmutableDictionary<TKey, TValue>.TryGetKey(equalKey, this.Origin, out actualKey);
}
private static Boolean TryGetKey(TKey equalKey, ImmutableDictionary<TKey, TValue>.MutationInput origin, out TKey actualKey)
{
ImmutableDictionary<TKey, TValue>.HashBucket tKeys;
Int32 hashCode = origin.KeyComparer.GetHashCode(equalKey);
if (!origin.Root.TryGetValue(hashCode, Comparer<Int32>.Default, out tKeys))
{
actualKey = equalKey;
return false;
}
return tKeys.TryGetKey(equalKey, origin.KeyOnlyComparer, out actualKey);
}
public Boolean TryGetValue(TKey key, out TValue value)
{
Requires.NotNullAllowStructs<TKey>(key, "key");
return ImmutableDictionary<TKey, TValue>.TryGetValue(key, this.Origin, out value);
}
private static Boolean TryGetValue(TKey key, ImmutableDictionary<TKey, TValue>.MutationInput origin, out TValue value)
{
ImmutableDictionary<TKey, TValue>.HashBucket tKeys;
Int32 hashCode = origin.KeyComparer.GetHashCode(key);
if (!origin.Root.TryGetValue(hashCode, Comparer<Int32>.Default, out tKeys))
{
value = default(TValue);
return false;
}
return tKeys.TryGetValue(key, origin.KeyOnlyComparer, out value);
}
private static ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node UpdateRoot(ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root, Int32 hashCode, ImmutableDictionary<TKey, TValue>.HashBucket newBucket, IEqualityComparer<ImmutableDictionary<TKey, TValue>.HashBucket> hashBucketComparer)
{
Boolean flag;
Boolean flag1;
if (newBucket.IsEmpty)
{
return root.Remove(hashCode, Comparer<Int32>.Default, out flag);
}
return root.SetItem(hashCode, newBucket, Comparer<Int32>.Default, hashBucketComparer, out flag1, out flag);
}
public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
if (keyComparer == null)
{
keyComparer = EqualityComparer<TKey>.Default;
}
if (valueComparer == null)
{
valueComparer = EqualityComparer<TValue>.Default;
}
if (this.KeyComparer != keyComparer)
{
ImmutableDictionary<TKey, TValue>.Comparers comparer = ImmutableDictionary<TKey, TValue>.Comparers.Get(keyComparer, valueComparer);
return (new ImmutableDictionary<TKey, TValue>(comparer)).AddRange(this, true);
}
if (this.ValueComparer == valueComparer)
{
return this;
}
ImmutableDictionary<TKey, TValue>.Comparers comparer1 = this.comparers.WithValueComparer(valueComparer);
return new ImmutableDictionary<TKey, TValue>(this.root, comparer1, this.count);
}
public ImmutableDictionary<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer)
{
return this.WithComparers(keyComparer, this.comparers.ValueComparer);
}
private static ImmutableDictionary<TKey, TValue> Wrap(ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root, ImmutableDictionary<TKey, TValue>.Comparers comparers, Int32 count)
{
Requires.NotNull<ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node>(root, "root");
Requires.NotNull<ImmutableDictionary<TKey, TValue>.Comparers>(comparers, "comparers");
Requires.Range(count >= 0, "count", null);
return new ImmutableDictionary<TKey, TValue>(root, comparers, count);
}
private ImmutableDictionary<TKey, TValue> Wrap(ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root, Int32 adjustedCountIfDifferentRoot)
{
if (root == null)
{
return this.Clear();
}
if (this.root == root)
{
return this;
}
if (root.IsEmpty)
{
return this.Clear();
}
return new ImmutableDictionary<TKey, TValue>(root, this.comparers, adjustedCountIfDifferentRoot);
}
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableDictionary<,>.Builder.DebuggerProxy))]
public sealed class Builder : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
{
private ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root;
private ImmutableDictionary<TKey, TValue>.Comparers comparers;
private Int32 count;
private ImmutableDictionary<TKey, TValue> immutable;
private Int32 version;
private Object syncRoot;
public Int32 Count
{
get
{
return this.count;
}
}
public TValue this[TKey key]
{
get
{
TValue tValue;
if (!this.TryGetValue(key, out tValue))
{
throw new KeyNotFoundException();
}
return tValue;
}
set
{
ImmutableDictionary<TKey, TValue>.MutationResult mutationResult = ImmutableDictionary<TKey, TValue>.Add(key, value, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.SetValue, this.Origin);
this.Apply(mutationResult);
}
}
public IEqualityComparer<TKey> KeyComparer
{
get
{
return this.comparers.KeyComparer;
}
set
{
Requires.NotNull<IEqualityComparer<TKey>>(value, "value");
if (value != this.KeyComparer)
{
ImmutableDictionary<TKey, TValue>.Comparers comparer = ImmutableDictionary<TKey, TValue>.Comparers.Get(value, this.ValueComparer);
ImmutableDictionary<TKey, TValue>.MutationInput mutationInput = new ImmutableDictionary<TKey, TValue>.MutationInput(ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node.EmptyNode, comparer, 0);
ImmutableDictionary<TKey, TValue>.MutationResult mutationResult = ImmutableDictionary<TKey, TValue>.AddRange(this, mutationInput, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.ThrowIfValueDifferent);
this.immutable = null;
this.comparers = comparer;
this.count = mutationResult.CountAdjustment;
this.Root = mutationResult.Root;
}
}
}
public IEnumerable<TKey> Keys
{
get
{
return this.root.Values.SelectMany<ImmutableDictionary<TKey, TValue>.HashBucket, KeyValuePair<TKey, TValue>>((ImmutableDictionary<TKey, TValue>.HashBucket b) => b).Select<KeyValuePair<TKey, TValue>, TKey>((KeyValuePair<TKey, TValue> kv) => kv.Key);
}
}
private ImmutableDictionary<TKey, TValue>.MutationInput Origin
{
get
{
return new ImmutableDictionary<TKey, TValue>.MutationInput(this.Root, this.comparers, this.count);
}
}
private ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node Root
{
get
{
return this.root;
}
set
{
ImmutableDictionary<TKey, TValue>.Builder builder = this;
builder.version = builder.version + 1;
if (this.root != value)
{
this.root = value;
this.immutable = null;
}
}
}
Boolean System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly
{
get
{
return false;
}
}
ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys
{
get
{
return this.Keys.ToArray<TKey>(this.Count);
}
}
ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values
{
get
{
return this.Values.ToArray<TValue>(this.Count);
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
Boolean System.Collections.ICollection.IsSynchronized
{
get
{
return false;
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
Object System.Collections.ICollection.SyncRoot
{
get
{
if (this.syncRoot == null)
{
Interlocked.CompareExchange<Object>(ref this.syncRoot, new Object(), null);
}
return this.syncRoot;
}
}
Boolean System.Collections.IDictionary.IsFixedSize
{
get
{
return false;
}
}
Boolean System.Collections.IDictionary.IsReadOnly
{
get
{
return false;
}
}
Object System.Collections.IDictionary.this[Object key]
{
get
{
return this[(TKey)key];
}
set
{
this[(TKey)key] = (TValue)value;
}
}
ICollection System.Collections.IDictionary.Keys
{
get
{
return this.Keys.ToArray<TKey>(this.Count);
}
}
ICollection System.Collections.IDictionary.Values
{
get
{
return this.Values.ToArray<TValue>(this.Count);
}
}
public IEqualityComparer<TValue> ValueComparer
{
get
{
return this.comparers.ValueComparer;
}
set
{
Requires.NotNull<IEqualityComparer<TValue>>(value, "value");
if (value != this.ValueComparer)
{
this.comparers = this.comparers.WithValueComparer(value);
this.immutable = null;
}
}
}
public IEnumerable<TValue> Values
{
get
{
return this.root.Values.SelectMany<ImmutableDictionary<TKey, TValue>.HashBucket, KeyValuePair<TKey, TValue>>((ImmutableDictionary<TKey, TValue>.HashBucket b) => b).Select<KeyValuePair<TKey, TValue>, TValue>((KeyValuePair<TKey, TValue> kv) => kv.Value).ToArray<TValue>(this.Count);
}
}
internal Int32 Version
{
get
{
return this.version;
}
}
internal Builder(ImmutableDictionary<TKey, TValue> map)
{
Requires.NotNull<ImmutableDictionary<TKey, TValue>>(map, "map");
this.root = map.root;
this.count = map.count;
this.comparers = map.comparers;
this.immutable = map;
}
public void Add(TKey key, TValue value)
{
ImmutableDictionary<TKey, TValue>.MutationResult mutationResult = ImmutableDictionary<TKey, TValue>.Add(key, value, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin);
this.Apply(mutationResult);
}
public void Add(KeyValuePair<TKey, TValue> item)
{
this.Add(item.Key, item.Value);
}
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
ImmutableDictionary<TKey, TValue>.MutationResult mutationResult = ImmutableDictionary<TKey, TValue>.AddRange(items, this.Origin, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.ThrowIfValueDifferent);
this.Apply(mutationResult);
}
private Boolean Apply(ImmutableDictionary<TKey, TValue>.MutationResult result)
{
this.Root = result.Root;
ImmutableDictionary<TKey, TValue>.Builder countAdjustment = this;
countAdjustment.count = countAdjustment.count + result.CountAdjustment;
return result.CountAdjustment != 0;
}
public void Clear()
{
this.Root = ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node.EmptyNode;
this.count = 0;
}
public Boolean Contains(KeyValuePair<TKey, TValue> item)
{
return ImmutableDictionary<TKey, TValue>.Contains(item, this.Origin);
}
public Boolean ContainsKey(TKey key)
{
return ImmutableDictionary<TKey, TValue>.ContainsKey(key, this.Origin);
}
public Boolean ContainsValue(TValue value)
{
return this.Values.Contains<TValue>(value, this.ValueComparer);
}
public ImmutableDictionary<TKey, TValue>.Enumerator GetEnumerator()
{
return new ImmutableDictionary<TKey, TValue>.Enumerator(this.root, this);
}
public TValue GetValueOrDefault(TKey key)
{
return this.GetValueOrDefault(key, default(TValue));
}
public TValue GetValueOrDefault(TKey key, TValue defaultValue)
{
TValue tValue;
Requires.NotNullAllowStructs<TKey>(key, "key");
if (this.TryGetValue(key, out tValue))
{
return tValue;
}
return defaultValue;
}
public Boolean Remove(TKey key)
{
ImmutableDictionary<TKey, TValue>.MutationResult mutationResult = ImmutableDictionary<TKey, TValue>.Remove(key, this.Origin);
return this.Apply(mutationResult);
}
public Boolean Remove(KeyValuePair<TKey, TValue> item)
{
if (!this.Contains(item))
{
return false;
}
return this.Remove(item.Key);
}
public void RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull<IEnumerable<TKey>>(keys, "keys");
foreach (TKey key in keys)
{
this.Remove(key);
}
}
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, Int32 arrayIndex)
{
Requires.NotNull<KeyValuePair<TKey, TValue>[]>(array, "array");
foreach (KeyValuePair<TKey, TValue> keyValuePair in this)
{
Int32 num = arrayIndex;
arrayIndex = num + 1;
array[num] = keyValuePair;
}
}
IEnumerator<KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
void System.Collections.ICollection.CopyTo(Array array, Int32 arrayIndex)
{
Requires.NotNull<Array>(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex", null);
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex", null);
foreach (KeyValuePair<TKey, TValue> keyValuePair in this)
{
Object dictionaryEntry = new DictionaryEntry((Object)keyValuePair.Key, (Object)keyValuePair.Value);
Int32[] numArray = new Int32[1];
Int32 num = arrayIndex;
arrayIndex = num + 1;
numArray[0] = num;
array.SetValue(dictionaryEntry, numArray);
}
}
void System.Collections.IDictionary.Add(Object key, Object value)
{
this.Add((TKey)key, (TValue)value);
}
Boolean System.Collections.IDictionary.Contains(Object key)
{
return this.ContainsKey((TKey)key);
}
IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
void System.Collections.IDictionary.Remove(Object key)
{
this.Remove((TKey)key);
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public ImmutableDictionary<TKey, TValue> ToImmutable()
{
if (this.immutable == null)
{
this.immutable = ImmutableDictionary<TKey, TValue>.Wrap(this.root, this.comparers, this.count);
}
return this.immutable;
}
public Boolean TryGetKey(TKey equalKey, out TKey actualKey)
{
return ImmutableDictionary<TKey, TValue>.TryGetKey(equalKey, this.Origin, out actualKey);
}
public Boolean TryGetValue(TKey key, out TValue value)
{
return ImmutableDictionary<TKey, TValue>.TryGetValue(key, this.Origin, out value);
}
private class DebuggerProxy
{
private readonly ImmutableDictionary<TKey, TValue>.Builder map;
private KeyValuePair<TKey, TValue>[] contents;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Contents
{
get
{
if (this.contents == null)
{
this.contents = this.map.ToArray<KeyValuePair<TKey, TValue>>(this.map.Count);
}
return this.contents;
}
}
public DebuggerProxy(ImmutableDictionary<TKey, TValue>.Builder map)
{
Requires.NotNull<ImmutableDictionary<TKey, TValue>.Builder>(map, "map");
this.map = map;
}
}
}
internal class Comparers : IEqualityComparer<ImmutableDictionary<TKey, TValue>.HashBucket>, IEqualityComparer<KeyValuePair<TKey, TValue>>
{
internal readonly static ImmutableDictionary<TKey, TValue>.Comparers Default;
private readonly IEqualityComparer<TKey> keyComparer;
private readonly IEqualityComparer<TValue> valueComparer;
internal IEqualityComparer<ImmutableDictionary<TKey, TValue>.HashBucket> HashBucketEqualityComparer
{
get
{
return this;
}
}
internal IEqualityComparer<TKey> KeyComparer
{
get
{
return this.keyComparer;
}
}
internal IEqualityComparer<KeyValuePair<TKey, TValue>> KeyOnlyComparer
{
get
{
return this;
}
}
internal IEqualityComparer<TValue> ValueComparer
{
get
{
return this.valueComparer;
}
}
static Comparers()
{
ImmutableDictionary<TKey, TValue>.Comparers.Default = new ImmutableDictionary<TKey, TValue>.Comparers(EqualityComparer<TKey>.Default, EqualityComparer<TValue>.Default);
}
internal Comparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull<IEqualityComparer<TKey>>(keyComparer, "keyComparer");
Requires.NotNull<IEqualityComparer<TValue>>(valueComparer, "valueComparer");
this.keyComparer = keyComparer;
this.valueComparer = valueComparer;
}
public Boolean Equals(ImmutableDictionary<TKey, TValue>.HashBucket x, ImmutableDictionary<TKey, TValue>.HashBucket y)
{
if (!Object.ReferenceEquals(x.AdditionalElements, y.AdditionalElements) || !this.KeyComparer.Equals(x.FirstValue.Key, y.FirstValue.Key))
{
return false;
}
IEqualityComparer<TValue> valueComparer = this.ValueComparer;
KeyValuePair<TKey, TValue> firstValue = x.FirstValue;
return valueComparer.Equals(firstValue.Value, y.FirstValue.Value);
}
internal static ImmutableDictionary<TKey, TValue>.Comparers Get(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull<IEqualityComparer<TKey>>(keyComparer, "keyComparer");
Requires.NotNull<IEqualityComparer<TValue>>(valueComparer, "valueComparer");
if (keyComparer == ImmutableDictionary<TKey, TValue>.Comparers.Default.KeyComparer && valueComparer == ImmutableDictionary<TKey, TValue>.Comparers.Default.ValueComparer)
{
return ImmutableDictionary<TKey, TValue>.Comparers.Default;
}
return new ImmutableDictionary<TKey, TValue>.Comparers(keyComparer, valueComparer);
}
public Int32 GetHashCode(ImmutableDictionary<TKey, TValue>.HashBucket obj)
{
return this.KeyComparer.GetHashCode(obj.FirstValue.Key);
}
Boolean System.Collections.Generic.IEqualityComparer<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Equals(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y)
{
return this.keyComparer.Equals(x.Key, y.Key);
}
Int32 System.Collections.Generic.IEqualityComparer<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetHashCode(KeyValuePair<TKey, TValue> obj)
{
return this.keyComparer.GetHashCode(obj.Key);
}
internal ImmutableDictionary<TKey, TValue>.Comparers WithValueComparer(IEqualityComparer<TValue> valueComparer)
{
Requires.NotNull<IEqualityComparer<TValue>>(valueComparer, "valueComparer");
if (this.valueComparer == valueComparer)
{
return this;
}
return ImmutableDictionary<TKey, TValue>.Comparers.Get(this.KeyComparer, valueComparer);
}
}
private class DebuggerProxy
{
private readonly ImmutableDictionary<TKey, TValue> map;
private KeyValuePair<TKey, TValue>[] contents;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Contents
{
get
{
if (this.contents == null)
{
this.contents = this.map.ToArray<KeyValuePair<TKey, TValue>>(this.map.Count);
}
return this.contents;
}
}
public DebuggerProxy(ImmutableDictionary<TKey, TValue> map)
{
Requires.NotNull<ImmutableDictionary<TKey, TValue>>(map, "map");
this.map = map;
}
}
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IEnumerator, IDisposable
{
private readonly ImmutableDictionary<TKey, TValue>.Builder builder;
private ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Enumerator mapEnumerator;
private ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator bucketEnumerator;
private Int32 enumeratingBuilderVersion;
public KeyValuePair<TKey, TValue> Current
{
get
{
this.mapEnumerator.ThrowIfDisposed();
return this.bucketEnumerator.Current;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
return this.Current;
}
}
internal Enumerator(ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root, ImmutableDictionary<TKey, TValue>.Builder builder = null)
{
this.builder = builder;
this.mapEnumerator = new ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Enumerator(root, null);
this.bucketEnumerator = new ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator();
this.enumeratingBuilderVersion = (builder != null ? builder.Version : -1);
}
public void Dispose()
{
this.mapEnumerator.Dispose();
this.bucketEnumerator.Dispose();
}
public Boolean MoveNext()
{
this.ThrowIfChanged();
if (this.bucketEnumerator.MoveNext())
{
return true;
}
if (!this.mapEnumerator.MoveNext())
{
return false;
}
this.bucketEnumerator = new ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator(this.mapEnumerator.Current.Value);
return this.bucketEnumerator.MoveNext();
}
public void Reset()
{
this.enumeratingBuilderVersion = (this.builder != null ? this.builder.Version : -1);
this.mapEnumerator.Reset();
this.bucketEnumerator.Dispose();
this.bucketEnumerator = new ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator();
}
private void ThrowIfChanged()
{
if (this.builder != null && this.builder.Version != this.enumeratingBuilderVersion)
{
throw new InvalidOperationException(Strings.CollectionModifiedDuringEnumeration);
}
}
}
internal struct HashBucket : IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IEquatable<ImmutableDictionary<TKey, TValue>.HashBucket>
{
private readonly KeyValuePair<TKey, TValue> firstValue;
private readonly ImmutableList<KeyValuePair<TKey, TValue>>.Node additionalElements;
internal ImmutableList<KeyValuePair<TKey, TValue>>.Node AdditionalElements
{
get
{
return this.additionalElements;
}
}
internal KeyValuePair<TKey, TValue> FirstValue
{
get
{
if (this.IsEmpty)
{
throw new InvalidOperationException();
}
return this.firstValue;
}
}
internal Boolean IsEmpty
{
get
{
return this.additionalElements == null;
}
}
private HashBucket(KeyValuePair<TKey, TValue> firstElement, ImmutableList<KeyValuePair<TKey, TValue>>.Node additionalElements = null)
{
this.firstValue = firstElement;
Object emptyNode = additionalElements;
if (emptyNode == null)
{
emptyNode = ImmutableList<KeyValuePair<TKey, TValue>>.Node.EmptyNode;
}
this.additionalElements = (ImmutableList<KeyValuePair<TKey, TValue>>.Node)emptyNode;
}
internal ImmutableDictionary<TKey, TValue>.HashBucket Add(TKey key, TValue value, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, IEqualityComparer<TValue> valueComparer, ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior behavior, out ImmutableDictionary<TKey, TValue>.OperationResult result)
{
KeyValuePair<TKey, TValue> keyValuePair = new KeyValuePair<TKey, TValue>(key, value);
if (this.IsEmpty)
{
result = ImmutableDictionary<TKey, TValue>.OperationResult.SizeChanged;
return new ImmutableDictionary<TKey, TValue>.HashBucket(keyValuePair, null);
}
if (keyOnlyComparer.Equals(keyValuePair, this.firstValue))
{
switch (behavior)
{
case (ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior)ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.SetValue:
{
result = ImmutableDictionary<TKey, TValue>.OperationResult.AppliedWithoutSizeChange;
return new ImmutableDictionary<TKey, TValue>.HashBucket(keyValuePair, this.additionalElements);
}
case (ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior)ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.Skip:
{
result = ImmutableDictionary<TKey, TValue>.OperationResult.NoChangeRequired;
return this;
}
case (ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior)ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.ThrowIfValueDifferent:
{
if (!valueComparer.Equals(this.firstValue.Value, value))
{
throw new ArgumentException(Strings.DuplicateKey);
}
result = ImmutableDictionary<TKey, TValue>.OperationResult.NoChangeRequired;
return this;
}
case (ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior)ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.ThrowAlways:
{
throw new ArgumentException(Strings.DuplicateKey);
}
}
throw new InvalidOperationException();
}
Int32 num = this.additionalElements.IndexOf(keyValuePair, keyOnlyComparer);
if (num < 0)
{
result = ImmutableDictionary<TKey, TValue>.OperationResult.SizeChanged;
return new ImmutableDictionary<TKey, TValue>.HashBucket(this.firstValue, this.additionalElements.Add(keyValuePair));
}
switch (behavior)
{
case (ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior)ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.SetValue:
{
result = ImmutableDictionary<TKey, TValue>.OperationResult.AppliedWithoutSizeChange;
return new ImmutableDictionary<TKey, TValue>.HashBucket(this.firstValue, this.additionalElements.ReplaceAt(num, keyValuePair));
}
case (ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior)ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.Skip:
{
result = ImmutableDictionary<TKey, TValue>.OperationResult.NoChangeRequired;
return this;
}
case (ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior)ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.ThrowIfValueDifferent:
{
if (!valueComparer.Equals(this.additionalElements[num].Value, value))
{
throw new ArgumentException(Strings.DuplicateKey);
}
result = ImmutableDictionary<TKey, TValue>.OperationResult.NoChangeRequired;
return this;
}
case (ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior)ImmutableDictionary<TKey, TValue>.KeyCollisionBehavior.ThrowAlways:
{
throw new ArgumentException(Strings.DuplicateKey);
}
}
throw new InvalidOperationException();
}
internal void Freeze()
{
if (this.additionalElements != null)
{
this.additionalElements.Freeze();
}
}
public ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator GetEnumerator()
{
return new ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator(this);
}
internal ImmutableDictionary<TKey, TValue>.HashBucket Remove(TKey key, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, out ImmutableDictionary<TKey, TValue>.OperationResult result)
{
if (this.IsEmpty)
{
result = ImmutableDictionary<TKey, TValue>.OperationResult.NoChangeRequired;
return this;
}
KeyValuePair<TKey, TValue> keyValuePair = new KeyValuePair<TKey, TValue>(key, default(TValue));
if (keyOnlyComparer.Equals(this.firstValue, keyValuePair))
{
if (this.additionalElements.IsEmpty)
{
result = ImmutableDictionary<TKey, TValue>.OperationResult.SizeChanged;
return new ImmutableDictionary<TKey, TValue>.HashBucket();
}
Int32 count = ((IBinaryTree<KeyValuePair<TKey, TValue>>)this.additionalElements).Left.Count;
result = ImmutableDictionary<TKey, TValue>.OperationResult.SizeChanged;
return new ImmutableDictionary<TKey, TValue>.HashBucket(this.additionalElements.Key, this.additionalElements.RemoveAt(count));
}
Int32 num = this.additionalElements.IndexOf(keyValuePair, keyOnlyComparer);
if (num < 0)
{
result = ImmutableDictionary<TKey, TValue>.OperationResult.NoChangeRequired;
return this;
}
result = ImmutableDictionary<TKey, TValue>.OperationResult.SizeChanged;
return new ImmutableDictionary<TKey, TValue>.HashBucket(this.firstValue, this.additionalElements.RemoveAt(num));
}
IEnumerator<KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
Boolean System.IEquatable<System.Collections.Immutable.ImmutableDictionary<TKey, TValue>.HashBucket>.Equals(ImmutableDictionary<TKey, TValue>.HashBucket other)
{
throw new Exception();
}
internal Boolean TryGetKey(TKey equalKey, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, out TKey actualKey)
{
if (this.IsEmpty)
{
actualKey = equalKey;
return false;
}
KeyValuePair<TKey, TValue> keyValuePair = new KeyValuePair<TKey, TValue>(equalKey, default(TValue));
if (keyOnlyComparer.Equals(this.firstValue, keyValuePair))
{
actualKey = this.firstValue.Key;
return true;
}
Int32 num = this.additionalElements.IndexOf(keyValuePair, keyOnlyComparer);
if (num < 0)
{
actualKey = equalKey;
return false;
}
actualKey = this.additionalElements[num].Key;
return true;
}
internal Boolean TryGetValue(TKey key, IEqualityComparer<KeyValuePair<TKey, TValue>> keyOnlyComparer, out TValue value)
{
if (this.IsEmpty)
{
value = default(TValue);
return false;
}
KeyValuePair<TKey, TValue> keyValuePair = new KeyValuePair<TKey, TValue>(key, default(TValue));
if (keyOnlyComparer.Equals(this.firstValue, keyValuePair))
{
value = this.firstValue.Value;
return true;
}
Int32 num = this.additionalElements.IndexOf(keyValuePair, keyOnlyComparer);
if (num < 0)
{
value = default(TValue);
return false;
}
value = this.additionalElements[num].Value;
return true;
}
internal struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IEnumerator, IDisposable
{
private readonly ImmutableDictionary<TKey, TValue>.HashBucket bucket;
private ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position currentPosition;
private ImmutableList<KeyValuePair<TKey, TValue>>.Enumerator additionalEnumerator;
public KeyValuePair<TKey, TValue> Current
{
get
{
switch (this.currentPosition)
{
case (ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position)ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.First:
{
return this.bucket.firstValue;
}
case (ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position)ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.Additional:
{
return this.additionalEnumerator.Current;
}
}
throw new InvalidOperationException();
}
}
Object System.Collections.IEnumerator.Current
{
get
{
return this.Current;
}
}
internal Enumerator(ImmutableDictionary<TKey, TValue>.HashBucket bucket)
{
this.bucket = bucket;
this.currentPosition = ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.BeforeFirst;
this.additionalEnumerator = new ImmutableList<KeyValuePair<TKey, TValue>>.Enumerator();
}
public void Dispose()
{
this.additionalEnumerator.Dispose();
}
public Boolean MoveNext()
{
if (this.bucket.IsEmpty)
{
this.currentPosition = ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.End;
return false;
}
switch (this.currentPosition)
{
case (ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position)ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.BeforeFirst:
{
this.currentPosition = ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.First;
return true;
}
case (ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position)ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.First:
{
if (this.bucket.additionalElements.IsEmpty)
{
this.currentPosition = ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.End;
return false;
}
this.currentPosition = ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.Additional;
this.additionalEnumerator = new ImmutableList<KeyValuePair<TKey, TValue>>.Enumerator(this.bucket.additionalElements, null, -1, -1, false);
return this.additionalEnumerator.MoveNext();
}
case (ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position)ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.Additional:
{
return this.additionalEnumerator.MoveNext();
}
case (ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position)ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.End:
{
return false;
}
}
throw new InvalidOperationException();
}
public void Reset()
{
this.additionalEnumerator.Dispose();
this.currentPosition = ImmutableDictionary<TKey, TValue>.HashBucket.Enumerator.Position.BeforeFirst;
}
private enum Position
{
BeforeFirst,
First,
Additional,
End
}
}
}
internal enum KeyCollisionBehavior
{
SetValue,
Skip,
ThrowIfValueDifferent,
ThrowAlways
}
private struct MutationInput
{
private readonly ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root;
private readonly ImmutableDictionary<TKey, TValue>.Comparers comparers;
private readonly Int32 count;
internal Int32 Count
{
get
{
return this.count;
}
}
internal IEqualityComparer<ImmutableDictionary<TKey, TValue>.HashBucket> HashBucketComparer
{
get
{
return this.comparers.HashBucketEqualityComparer;
}
}
internal IEqualityComparer<TKey> KeyComparer
{
get
{
return this.comparers.KeyComparer;
}
}
internal IEqualityComparer<KeyValuePair<TKey, TValue>> KeyOnlyComparer
{
get
{
return this.comparers.KeyOnlyComparer;
}
}
internal ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node Root
{
get
{
return this.root;
}
}
internal IEqualityComparer<TValue> ValueComparer
{
get
{
return this.comparers.ValueComparer;
}
}
internal MutationInput(ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root, ImmutableDictionary<TKey, TValue>.Comparers comparers, Int32 count)
{
this.root = root;
this.comparers = comparers;
this.count = count;
}
internal MutationInput(ImmutableDictionary<TKey, TValue> map)
{
this.root = map.root;
this.comparers = map.comparers;
this.count = map.count;
}
}
private struct MutationResult
{
private readonly ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root;
private readonly Int32 countAdjustment;
internal Int32 CountAdjustment
{
get
{
return this.countAdjustment;
}
}
internal ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node Root
{
get
{
return this.root;
}
}
internal MutationResult(ImmutableDictionary<TKey, TValue>.MutationInput unchangedInput)
{
this.root = unchangedInput.Root;
this.countAdjustment = 0;
}
internal MutationResult(ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node root, Int32 countAdjustment)
{
Requires.NotNull<ImmutableSortedDictionary<Int32, ImmutableDictionary<TKey, TValue>.HashBucket>.Node>(root, "root");
this.root = root;
this.countAdjustment = countAdjustment;
}
internal ImmutableDictionary<TKey, TValue> Finalize(ImmutableDictionary<TKey, TValue> priorMap)
{
Requires.NotNull<ImmutableDictionary<TKey, TValue>>(priorMap, "priorMap");
return priorMap.Wrap(this.Root, priorMap.count + this.CountAdjustment);
}
}
internal enum OperationResult
{
AppliedWithoutSizeChange,
SizeChanged,
NoChangeRequired
}
}
} |
using Refit;
using System.Threading.Tasks;
namespace Consulta
{
public interface ICepAPI
{
[Get ("/ws/{cep}/json")]
Task<CEPClass> GetAddressASync(string cep);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace QuestStudio
{
public class StructReader
{
private static int GetTypeSize(Type T)
{
if (T == typeof(byte) || T == typeof(sbyte) || T == typeof(bool))
return 1;
else if (T == typeof(ushort) || T == typeof(short))
return 2;
else if (T == typeof(uint) || T == typeof(int))
return 4;
else if (T == typeof(ulong) || T == typeof(long))
return 8;
throw new FooException("GetTypeSize::Unknown Type");
}
private static int FixAlignment(ref int Offset, Type datatype)
{
int SizeOfType = GetTypeSize(datatype);
//Console.WriteLine("Reading {0} at Offset {1} (size={2})", datatype, Offset, SizeOfType);
int PaddedOffset = Offset;
if (Offset % SizeOfType != 0) // misaligned
PaddedOffset += (SizeOfType - (Offset % SizeOfType));
Offset = PaddedOffset + SizeOfType; // update the ref parameter
//Console.WriteLine("Read from: {0}, Next Object at {1}", PaddedOffset, Offset);
return PaddedOffset;
}
T CreateType<T>() where T : new()
{
return new T();
}
public static object BytesToObject(byte[] data, ref int offs, Type dt)
{
if (dt == typeof(bool))
return (bool)(data[FixAlignment(ref offs, dt)] != 0);
else if (dt == typeof(sbyte))
return (sbyte)data[FixAlignment(ref offs, dt)];
else if (dt == typeof(byte))
return (byte)data[FixAlignment(ref offs, dt)];
else if (dt == typeof(short))
return BitConverter.ToInt16(data, FixAlignment(ref offs, dt));
else if (dt == typeof(int))
return BitConverter.ToInt32(data, FixAlignment(ref offs, dt));
else if (dt == typeof(long))
return BitConverter.ToInt64(data, FixAlignment(ref offs, dt));
else if (dt == typeof(ushort))
return BitConverter.ToUInt16(data, FixAlignment(ref offs, dt));
else if (dt == typeof(uint))
return BitConverter.ToUInt32(data, FixAlignment(ref offs, dt));
else if (dt == typeof(ulong))
return BitConverter.ToUInt64(data, FixAlignment(ref offs, dt));
else if (dt == typeof(string))
{
BitConverter.ToInt16(data, FixAlignment(ref offs, typeof(short))); // unused
int length = 0;
while (data[offs + length] != '\0')
length++;
string str = Encoding.GetEncoding("EUC-KR").GetString(data, offs, length);
offs += length + 1;
return str;
}
else if (dt.IsArray)
{
int dataCount = BitConverter.ToInt32(data, FixAlignment(ref offs, typeof(int)));
if (dataCount > 1 && data.Length <= 20)
dataCount = 1; // one file has a bugged action
Array arr = Array.CreateInstance(dt.GetElementType(), dataCount);
for (int i = 0; i < dataCount; i++)
{
object o = Activator.CreateInstance(dt.GetElementType());
StructReader.GetFields(data, ref offs, ref o);
arr.SetValue(o, i);
}
return arr;
}
else if (dt.IsEnum)
{
object value = BytesToObject(data, ref offs, Enum.GetUnderlyingType(dt));
return Enum.Parse(dt, value.ToString());
}
else
{
throw new FooException("Reading Unknown DataType " + dt);
}
}
public static void GetFields(byte[] data, ref int index, ref object Obj)
{
//Console.WriteLine("###" + Obj.GetType().ToString() + "###");
FieldInfo[] myFieldInfo = Obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
foreach (FieldInfo f in myFieldInfo)
{
Object value = BytesToObject(data, ref index, f.FieldType);
f.SetValue(Obj, value);
//Console.WriteLine("[{3}] Name: {0}, FieldType: {1}, Value: {2}", f.Name, f.FieldType, value, index);
}
// structure is padded so the total length is a multiple of the largest member size
if (index % 4 != 0)
{
index += (4 - (index % 4));
}
}
public static void Convert(byte[] data, ref object Obj)
{
int index = 0;
GetFields(data, ref index, ref Obj);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace SierraLib.Translation
{
public interface ITranslation
{
CultureInfo Culture { get; }
string Author { get; }
string this[string key] { get; }
string this[string key, string defaultValue] { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace babyloan.API.infrastructure.fineract.commons
{
public class user
{
public string fname {get;set;}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Collections.ObjectModel;
namespace solution1.Inventaire
{
public partial class choix_cpt : Form
{
MDIParent parent = null;
string connectionString = ConfigurationManager.ConnectionStrings["connectString1"].ConnectionString;
public struct structinvent
{
string idInvent;
string Invent;
public structinvent(String idinv, string inv) { this.idInvent = idinv; this.Invent = inv; }
public string idinvent
{
get { return idInvent; }
}
public string invent
{
get { return Invent; }
}
}
public choix_cpt(MDIParent parent)
{
this.parent = parent;
InitializeComponent();
charger_inv();
}
private void invent_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void charger_inv()
{
DataSet dinvent = MaConnexion.ExecuteSelect(connectionString, "select * from inventaire where type='Comptable' and caract='Cloturé'");
foreach (DataRow row in dinvent.Tables[0].Rows)
{
structinvent str = new structinvent(row[0].ToString(), row[1].ToString());
invent.Items.Add(str);
}
}
private void Importation_Click(object sender, EventArgs e)
{
NouvelInventaire nv_inv = new NouvelInventaire(parent);
nv_inv.type.Text = "Comptable";
nv_inv.Show();
}
private void cree_inv_Click(object sender, EventArgs e)
{
if(invent.Text != "")
{
string idinventaire = ((structinvent)invent.SelectedItem).idinvent;
string desiginvent = ((structinvent)invent.SelectedItem).invent;
string requete_insert1 = " INSERT INTO Inventaire (UIdInventaire ,DesigInventaire ,DateInventaire ,etat,type,caract) VALUES (NEWID(), '" +
tb_nom_inv.Text.ToString()+"', '" + DateTime.Now.ToString("dd/MM/yyyy H:m:s") + "', 'Valide','Comptable','En cours')";
if (MaConnexion.ExecuteUpdate(connectionString, requete_insert1) == 1)
{
bool import = false;
string requete_id_inventaire = "select UIdInventaire from Inventaire where DateInventaire=(SELECT MAX(DateInventaire)FROM Inventaire)";
DataSet id_inventaire = MaConnexion.ExecuteSelect(connectionString, requete_id_inventaire);
string id_invent = id_inventaire.Tables[0].Rows[0][0].ToString();
string requete_inv = "select * from SeTrouveB where uidInventaire='" + idinventaire.ToString().Trim() + "'";
DataSet setrouve = MaConnexion.ExecuteSelect(connectionString, requete_inv);
if (setrouve.Tables[0].Rows.Count > 0)
{
foreach (DataRow ligne in setrouve.Tables[0].Rows)
{
string req_insert = "INSERT INTO SeTrouveB (uidInventaire,IdSite,IdEmpla,IdBien,IdEtat) VALUES ('" + id_invent.ToString() + "'," + ligne[1] + ",'" + ligne[2] + "','" + ligne[3] + "'," + ligne[4] + ")";
MaConnexion.ExecuteUpdate(connectionString, req_insert);
}
MessageBox.Show("La création d'inventaire est effectuée avec succès");
}
}
else { MessageBox.Show("Erreur d'importation"); }
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Globalization;
namespace Server.Items
{
public class Platinum : Item
{
public override double DefaultWeight
{
get { return ( 0.02 ); }
}
[Constructable]
public Platinum() : this( 1 )
{
}
[Constructable]
public Platinum( int amountFrom, int amountTo ) : this( Utility.RandomMinMax( amountFrom, amountTo ) )
{
}
[Constructable]
public Platinum( int amount ) : base( 0xEED )
{
Name = "platinum";
Hue = 2101;
Stackable = true;
Amount = amount;
LootType = LootType.Blessed;
ItemValue = ItemValue.Legendary;
}
public Platinum( Serial serial ) : base( serial )
{
}
public override void GetProperties( ObjectPropertyList list )
{
base.GetProperties( list );
decimal amount = this.Amount * 0.10m;
string newAmount = amount.ToString( "C", CultureInfo.GetCultureInfo( "en-US" ) );
list.Add( 1053099, "{0}\t{1}", newAmount, "USD" );
}
public override int GetDropSound()
{
if ( Amount <= 1 )
return 0x2E4;
else if ( Amount <= 5 )
return 0x2E5;
else
return 0x2E6;
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} |
using System.Windows;
using System.Windows.Controls;
using Verbos.Logic;
namespace Verbos.UserCtrl
{
/// <summary>
/// Interaction logic for RegisterControl.xaml
/// </summary>
public partial class RegisterControl : UserControl
{
private UserLogic ul = new UserLogic();
public RegisterControl()
{
InitializeComponent();
}
//string user, string firstname, string lastname, string email, string addresse, int postleitzahl, string tel, DateTime geb, string password, string passwordCompare
private void btn_register_Click(object sender, RoutedEventArgs e)
{
if (ul.register(tb_Username.Text, tb_Vorname.Text, tb_Nachname.Text, tb_Email.Text, tb_Addresse.Text, tb_Postleitzahl.Text, tb_Telefon.Text, date_geb.SelectedDate.Value, p_Password1.Password , p_Password2.Password))
{
User us = ul.getUser(tb_Username.Text);
foreach (Window w in Application.Current.Windows)
{
if (w.GetType() == typeof(MainWindow))
{
(w as MainWindow).Username.Text = us.Username;
(w as MainWindow).Name.Text = us.Vorname;
(w as MainWindow).Nachname.Text = us.Nachname;
}
}
clearAll();
ERROR.Text = "Willkommen!";
}else
{
ERROR.Text = "Versuchen Sie es bitte erneut";
}
}
private void clearAll()
{
tb_Addresse.Text = null;
tb_Email.Text = null;
tb_Nachname.Text = null;
tb_Postleitzahl.Text = null;
tb_Telefon.Text = null;
tb_Username.Text = null;
tb_Vorname.Text = null;
p_Password1.Password = null;
p_Password2.Password = null;
date_geb.SelectedDate = null;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
clearAll();
}
}
}
|
using ArrayExtensions.ArraySort;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrayExtensions.ArraySearch
{
public static class Search
{
public static int BinarySearch<T>(this T[] arrayOfElems, T keyElem,IComparer<T> comparer)
{
if (arrayOfElems is null)
{
throw new ArgumentNullException(nameof(arrayOfElems));
}
if (comparer is null)
{
throw new ArgumentNullException(nameof(comparer));
}
if (arrayOfElems.Length == 0)
{
throw new ArgumentOutOfRangeException(nameof(arrayOfElems));
}
int orderOfArray = comparer.Compare(arrayOfElems[0],arrayOfElems[arrayOfElems.Length - 1]);
return BinarySearchRecourse(orderOfArray, arrayOfElems, keyElem, 0, arrayOfElems.Length,comparer);
}
private static int BinarySearchRecourse<T>(int directionOfArray, T[] arrayOfElems,T keyElem,int leftElement,int rightElement,IComparer<T> comparer)
{
if (leftElement == rightElement)
{
return -1;
}
int middleElement = leftElement + (rightElement - leftElement) / 2;
if (comparer.Compare(keyElem,arrayOfElems[leftElement]) == 0)
{
return leftElement;
}
if (comparer.Compare(keyElem,arrayOfElems[middleElement]) == 0)
{
if (middleElement + 1 == leftElement)
{
return middleElement;
}
else
{
return BinarySearchRecourse(directionOfArray, arrayOfElems, keyElem, leftElement, middleElement + 1,comparer);
}
}
if ((comparer.Compare(arrayOfElems[middleElement],keyElem) ^ directionOfArray) == 1)
{
return BinarySearchRecourse(directionOfArray, arrayOfElems, keyElem, leftElement, middleElement,comparer);
}
else
{
return BinarySearchRecourse(directionOfArray, arrayOfElems, keyElem, middleElement + 1, rightElement,comparer);
}
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace HINVenture.Shared.Migrations
{
public partial class CheckUsers : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_CustomerUser_AspNetUsers_Id",
table: "CustomerUser");
migrationBuilder.DropForeignKey(
name: "FK_FreelancerUser_AspNetUsers_Id",
table: "FreelancerUser");
migrationBuilder.DropForeignKey(
name: "FK_Messages_CustomerUser_CustomerId",
table: "Messages");
migrationBuilder.DropForeignKey(
name: "FK_Messages_FreelancerUser_FreelancerId",
table: "Messages");
migrationBuilder.DropForeignKey(
name: "FK_OrderProgresses_FreelancerUser_FreelancerId",
table: "OrderProgresses");
migrationBuilder.DropForeignKey(
name: "FK_Orders_FreelancerUser_CurrentFreelancerId",
table: "Orders");
migrationBuilder.DropForeignKey(
name: "FK_Orders_CustomerUser_CustomerId",
table: "Orders");
migrationBuilder.DropForeignKey(
name: "FK_Specialities_FreelancerUser_FreelancerUserId",
table: "Specialities");
migrationBuilder.DropPrimaryKey(
name: "PK_FreelancerUser",
table: "FreelancerUser");
migrationBuilder.DropPrimaryKey(
name: "PK_CustomerUser",
table: "CustomerUser");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "0b11086a-dac7-43a3-9eb8-b43242da8f69");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "0d046923-6890-4e2a-a29d-7cdc44e2dd1e");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "3e1494ad-f065-4802-8b47-9b1e17471ec7");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "56f5e664-821e-4793-b0a0-63a33b1de6f8");
migrationBuilder.RenameTable(
name: "FreelancerUser",
newName: "FreelancerUsers");
migrationBuilder.RenameTable(
name: "CustomerUser",
newName: "CustomerUsers");
migrationBuilder.AddPrimaryKey(
name: "PK_FreelancerUsers",
table: "FreelancerUsers",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_CustomerUsers",
table: "CustomerUsers",
column: "Id");
migrationBuilder.InsertData(
table: "AspNetRoles",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[,]
{
{ "5d763f81-c499-44d8-a3a4-6a90e5c34eb3", "37619d5b-4696-4260-8c7e-aa637acae354", "freelancer", "FREELANCER" },
{ "dec2fab1-a4ca-4812-88af-ab42edb26ad4", "94bdf15b-34b3-4954-a2c9-54b99ecfe346", "customer", "CUSTOMER" },
{ "ec41838d-388f-4ef3-a866-e874adf1ec28", "ba3d09f8-d363-41aa-83b3-338580887572", "senior", "SENIOR" },
{ "296d8d9b-3dd9-437a-b649-a04b713db08f", "5d7faf6d-b163-4b61-896d-b311a25885d3", "admin", "ADMIN" }
});
migrationBuilder.AddForeignKey(
name: "FK_CustomerUsers_AspNetUsers_Id",
table: "CustomerUsers",
column: "Id",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_FreelancerUsers_AspNetUsers_Id",
table: "FreelancerUsers",
column: "Id",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Messages_CustomerUsers_CustomerId",
table: "Messages",
column: "CustomerId",
principalTable: "CustomerUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Messages_FreelancerUsers_FreelancerId",
table: "Messages",
column: "FreelancerId",
principalTable: "FreelancerUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrderProgresses_FreelancerUsers_FreelancerId",
table: "OrderProgresses",
column: "FreelancerId",
principalTable: "FreelancerUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Orders_FreelancerUsers_CurrentFreelancerId",
table: "Orders",
column: "CurrentFreelancerId",
principalTable: "FreelancerUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Orders_CustomerUsers_CustomerId",
table: "Orders",
column: "CustomerId",
principalTable: "CustomerUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Specialities_FreelancerUsers_FreelancerUserId",
table: "Specialities",
column: "FreelancerUserId",
principalTable: "FreelancerUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_CustomerUsers_AspNetUsers_Id",
table: "CustomerUsers");
migrationBuilder.DropForeignKey(
name: "FK_FreelancerUsers_AspNetUsers_Id",
table: "FreelancerUsers");
migrationBuilder.DropForeignKey(
name: "FK_Messages_CustomerUsers_CustomerId",
table: "Messages");
migrationBuilder.DropForeignKey(
name: "FK_Messages_FreelancerUsers_FreelancerId",
table: "Messages");
migrationBuilder.DropForeignKey(
name: "FK_OrderProgresses_FreelancerUsers_FreelancerId",
table: "OrderProgresses");
migrationBuilder.DropForeignKey(
name: "FK_Orders_FreelancerUsers_CurrentFreelancerId",
table: "Orders");
migrationBuilder.DropForeignKey(
name: "FK_Orders_CustomerUsers_CustomerId",
table: "Orders");
migrationBuilder.DropForeignKey(
name: "FK_Specialities_FreelancerUsers_FreelancerUserId",
table: "Specialities");
migrationBuilder.DropPrimaryKey(
name: "PK_FreelancerUsers",
table: "FreelancerUsers");
migrationBuilder.DropPrimaryKey(
name: "PK_CustomerUsers",
table: "CustomerUsers");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "296d8d9b-3dd9-437a-b649-a04b713db08f");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "5d763f81-c499-44d8-a3a4-6a90e5c34eb3");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "dec2fab1-a4ca-4812-88af-ab42edb26ad4");
migrationBuilder.DeleteData(
table: "AspNetRoles",
keyColumn: "Id",
keyValue: "ec41838d-388f-4ef3-a866-e874adf1ec28");
migrationBuilder.RenameTable(
name: "FreelancerUsers",
newName: "FreelancerUser");
migrationBuilder.RenameTable(
name: "CustomerUsers",
newName: "CustomerUser");
migrationBuilder.AddPrimaryKey(
name: "PK_FreelancerUser",
table: "FreelancerUser",
column: "Id");
migrationBuilder.AddPrimaryKey(
name: "PK_CustomerUser",
table: "CustomerUser",
column: "Id");
migrationBuilder.InsertData(
table: "AspNetRoles",
columns: new[] { "Id", "ConcurrencyStamp", "Name", "NormalizedName" },
values: new object[,]
{
{ "3e1494ad-f065-4802-8b47-9b1e17471ec7", "2636887f-9bb8-4b72-8d2e-c8af95551b1a", "freelancer", "FREELANCER" },
{ "0d046923-6890-4e2a-a29d-7cdc44e2dd1e", "0b47c6b5-592c-4642-b01e-516a763d99cb", "customer", "CUSTOMER" },
{ "56f5e664-821e-4793-b0a0-63a33b1de6f8", "9575aacd-68c1-47dd-9eee-05a0ee088e72", "senior", "SENIOR" },
{ "0b11086a-dac7-43a3-9eb8-b43242da8f69", "1c6a7bca-a0db-47be-b955-cea53c8bc34a", "admin", "ADMIN" }
});
migrationBuilder.AddForeignKey(
name: "FK_CustomerUser_AspNetUsers_Id",
table: "CustomerUser",
column: "Id",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_FreelancerUser_AspNetUsers_Id",
table: "FreelancerUser",
column: "Id",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Messages_CustomerUser_CustomerId",
table: "Messages",
column: "CustomerId",
principalTable: "CustomerUser",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Messages_FreelancerUser_FreelancerId",
table: "Messages",
column: "FreelancerId",
principalTable: "FreelancerUser",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrderProgresses_FreelancerUser_FreelancerId",
table: "OrderProgresses",
column: "FreelancerId",
principalTable: "FreelancerUser",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Orders_FreelancerUser_CurrentFreelancerId",
table: "Orders",
column: "CurrentFreelancerId",
principalTable: "FreelancerUser",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Orders_CustomerUser_CustomerId",
table: "Orders",
column: "CustomerId",
principalTable: "CustomerUser",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Specialities_FreelancerUser_FreelancerUserId",
table: "Specialities",
column: "FreelancerUserId",
principalTable: "FreelancerUser",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BE;
namespace DS
{
public class DataSource
{
public static List<Order> listOfOrders = new List<Order>
{
new Order
{
}
};
public static List<GuestRequest> listOfRequests = new List<GuestRequest>
{
new BE.GuestRequest
{
PrivateName="שלומי",FamilyName="בן",MailAddress="shlo@gmail.com",Status=true,
RegistrationDate=new DateTime(2020,01,14),EntryDate=new DateTime(2019,01,01),
ReleaseDate=new DateTime(2019,01,03),Area=AREA.Jerusalem,Type=TYPE.Camping,
Adults=2,Children=0,Pool=true,ChildrenAttractions=false,GuestRequestKey=10000006
},
new BE.GuestRequest()
{
PrivateName="חיים",FamilyName="כהן",MailAddress="cha@gmail.com",Status=true,
RegistrationDate=new DateTime(2019,04,14),EntryDate=new DateTime(2019,05,10),
ReleaseDate=new DateTime(2019,05,16),Area=AREA.Center,Type=TYPE.Hotel,
Adults=2,Children=2,Pool=true,ChildrenAttractions=false,GuestRequestKey=10000005
}
};
public static List<Host> listOfHosts = new List<Host>
{
new BE.Host()
{
PrivateName="יעקב",FamilyName="דניאלי",PhoneNumber="05065168456",
MailAddress ="12yaacc@yahoo.com",BankAccountNumber="701326",
CollectionClearance =true
},
new BE.Host()
{
PrivateName="חגי",FamilyName="דויד",PhoneNumber="0591356482",
MailAddress ="chgi@gmail.com",BankAccountNumber="7012394",
CollectionClearance =true
},
};
public static List<HostingUnit> listOfUnits = new List<HostingUnit>
{
new BE.HostingUnit
{
HostingUnitName="בראשית",Type=TYPE.Hotel,Area=AREA.Jerusalem,Owner=new Host()
{
PrivateName="יעקב",FamilyName="דניאלי",PhoneNumber="05065168456",
MailAddress ="12yaacc@yahoo.com",BankAccountNumber="701326",
CollectionClearance =true
}
},
new BE.HostingUnit()
{
HostingUnitName="שמות",Type=TYPE.Zimmer,Area=AREA.South, Owner=new Host()
{
PrivateName="חגי",FamilyName="דויד",PhoneNumber="0591356482",
MailAddress ="chgi@gmail.com",BankAccountNumber="7012394",
CollectionClearance =true
},
},
};
}
}
|
using System;
using System.Text;
using SnakeGameConsole.Models;
using SnakeGameConsole.Interfaces;
namespace SnakeGameConsole.Services
{
public class MainMenuService : IMainMenuService
{
public void ShowMenu(Game game)
{
var scene = BuildScene(game);
Console.Write(scene);
Console.ReadKey();
}
private string BuildScene(Game game)
{
var scene = new StringBuilder();
for (int i = 0; i < game.Boundary.Height - 1; i++)
{
for (int j = 0; j < game.Boundary.Width - 1; j++)
{
if (i == 0)
{
scene.Append("#");
}
else if (i == 3 && j == 0)
{
scene.Append("SNAKE GAME");
}
else if (i == 5 && j == 0)
{
scene.Append("Press any key to continue...");
}
}
scene.Append(Environment.NewLine);
}
return scene.ToString();
}
}
}
|
using LuaInterface;
using SLua;
using System;
public class Lua_FunctionTyrantdb : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
FunctionTyrantdb o = new FunctionTyrantdb();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Initialize(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
string app_id;
LuaObject.checkType(l, 2, out app_id);
string channel;
LuaObject.checkType(l, 3, out channel);
string version;
LuaObject.checkType(l, 4, out version);
functionTyrantdb.Initialize(app_id, channel, version);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Resume(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
functionTyrantdb.Resume();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Stop(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
functionTyrantdb.Stop();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetUser(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
string user_id;
LuaObject.checkType(l, 2, out user_id);
FunctionTyrantdb.E_UserType user_type;
LuaObject.checkEnum<FunctionTyrantdb.E_UserType>(l, 3, out user_type);
FunctionTyrantdb.E_UserSex user_sex;
LuaObject.checkEnum<FunctionTyrantdb.E_UserSex>(l, 4, out user_sex);
int user_age;
LuaObject.checkType(l, 5, out user_age);
string user_name;
LuaObject.checkType(l, 6, out user_name);
functionTyrantdb.SetUser(user_id, user_type, user_sex, user_age, user_name);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetLevel(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
int level;
LuaObject.checkType(l, 2, out level);
functionTyrantdb.SetLevel(level);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetServer(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
string server;
LuaObject.checkType(l, 2, out server);
functionTyrantdb.SetServer(server);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Charge(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
string order_id;
LuaObject.checkType(l, 2, out order_id);
string product_name;
LuaObject.checkType(l, 3, out product_name);
int amount;
LuaObject.checkType(l, 4, out amount);
string currency_type;
LuaObject.checkType(l, 5, out currency_type);
int virtual_currency_amount;
LuaObject.checkType(l, 6, out virtual_currency_amount);
string pay_way;
LuaObject.checkType(l, 7, out pay_way);
functionTyrantdb.Charge(order_id, product_name, amount, currency_type, virtual_currency_amount, pay_way);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ChargeSuccess(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 2)
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
string order_id;
LuaObject.checkType(l, 2, out order_id);
functionTyrantdb.ChargeSuccess(order_id);
LuaObject.pushValue(l, true);
result = 1;
}
else if (num == 7)
{
FunctionTyrantdb functionTyrantdb2 = (FunctionTyrantdb)LuaObject.checkSelf(l);
string order_id2;
LuaObject.checkType(l, 2, out order_id2);
string product_name;
LuaObject.checkType(l, 3, out product_name);
int amount;
LuaObject.checkType(l, 4, out amount);
string currency_type;
LuaObject.checkType(l, 5, out currency_type);
int virtual_currency_amount;
LuaObject.checkType(l, 6, out virtual_currency_amount);
string pay_way;
LuaObject.checkType(l, 7, out pay_way);
functionTyrantdb2.ChargeSuccess(order_id2, product_name, amount, currency_type, virtual_currency_amount, pay_way);
LuaObject.pushValue(l, true);
result = 1;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ChargeFail(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
string order_id;
LuaObject.checkType(l, 2, out order_id);
string fail_reason;
LuaObject.checkType(l, 3, out fail_reason);
functionTyrantdb.ChargeFail(order_id, fail_reason);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int OnCreateRole(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
string str;
LuaObject.checkType(l, 2, out str);
functionTyrantdb.OnCreateRole(str);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int ChargeTo3rd(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
string order_id;
LuaObject.checkType(l, 2, out order_id);
int amount;
LuaObject.checkType(l, 3, out amount);
string currency_type;
LuaObject.checkType(l, 4, out currency_type);
string payment;
LuaObject.checkType(l, 5, out payment);
functionTyrantdb.ChargeTo3rd(order_id, amount, currency_type, payment);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetAppVersion(IntPtr l)
{
int result;
try
{
FunctionTyrantdb functionTyrantdb = (FunctionTyrantdb)LuaObject.checkSelf(l);
string appVersion = functionTyrantdb.GetAppVersion();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, appVersion);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_Instance(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, FunctionTyrantdb.Instance);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "FunctionTyrantdb");
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.Initialize));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.Resume));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.Stop));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.SetUser));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.SetLevel));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.SetServer));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.Charge));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.ChargeSuccess));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.ChargeFail));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.OnCreateRole));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.ChargeTo3rd));
LuaObject.addMember(l, new LuaCSFunction(Lua_FunctionTyrantdb.GetAppVersion));
LuaObject.addMember(l, "Instance", new LuaCSFunction(Lua_FunctionTyrantdb.get_Instance), null, false);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_FunctionTyrantdb.constructor), typeof(FunctionTyrantdb), typeof(Singleton<FunctionTyrantdb>));
}
}
|
using System;
using Xamarin.Forms;
using System.ComponentModel;
namespace Journal
{
public class BaseViewModel : INotifyPropertyChanged
{
public BaseViewModel()
{
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
|
using OmniSharp.Extensions.LanguageServer.Protocol.Serialization;
using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities;
namespace OmniSharp.Extensions.LanguageServer.Protocol.Models
{
public interface ITextDocumentSyncOptions
{
[Optional] bool OpenClose { get; set; }
[Optional] TextDocumentSyncKind Change { get; set; }
[Optional] bool WillSave { get; set; }
[Optional] bool WillSaveWaitUntil { get; set; }
[Optional] BooleanOr<SaveOptions> Save { get; set; }
}
}
|
using UnityEngine;
using UnityEngine.AI;
public class ZombieAnimation : MonoBehaviour
{
[Header("Local")]
private NavMeshAgent agent;
private Animator animator;
private bool isBiting;
[Header("Const")]
private const float distance = 1f;
private void Awake()
{
GetComponent<Zombie>().Animation += Animation;
GetComponent<ZombieDeath>().Die += Die;
GetComponent<ZombieDeath>().Spawn += Spawn;
animator = GetComponent<Animator>();
agent = GetComponent<NavMeshAgent>();
}
private void Die(bool isDying)
{
agent.isStopped = true;
isDying = true;
isBiting = false;
animator.SetBool("isBiting", isBiting);
animator.SetBool("isDying", isDying);
}
private void Spawn(bool isDying)
{
isDying = false;
animator.SetBool("isDying", isDying);
agent.isStopped = false;
}
private void Animation()
{
if (agent.remainingDistance > 0 && agent.remainingDistance <= distance)
{
isBiting = true;
}
if (agent.remainingDistance > 0 && agent.remainingDistance > distance)
{
isBiting = false;
}
animator.SetBool("isBiting", isBiting);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Gomoku {
public class RandomAI
: IAI {
public Tuple<uint, uint> MakeMove(Board board) {
Random r = new Random();
var moves = board.PossibleMoves();
var move = moves.ElementAt(r.Next(moves.Count() - 1));
return move;
}
}
}
|
using UnityEngine;
public class Target : MonoBehaviour
{
public float health = 50f;
//public HealthTower torre;
public void Takedam(float cant)
{
health -= cant;
if(health <=0)
{
Die();
}
}
void Die()
{
Destroy(gameObject);
PlayerManager.Killcount++;
}
void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Bate"))
{
health -= 50f;
}
if(other.CompareTag("Tower"))
{
Die();
HealthTower.vidatorre -= 3;
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.CompareTag("Tower"))
{
Die();
//torre.Vidatorre -= 5;
HealthTower.vidatorre -= 3;
}
}
}
|
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RO
{
[Serializable]
public class SmoothColor
{
public List<Color> colors;
public float duration = 1f;
private float progress;
public Color currentColor
{
get;
private set;
}
public bool valid
{
get
{
return 0f < this.duration && this.colors != null && 0 < this.colors.get_Count();
}
}
public bool Update()
{
if (!this.valid)
{
return false;
}
this.progress += Time.get_deltaTime() / this.duration;
if ((float)this.colors.get_Count() < this.progress)
{
this.progress -= (float)this.colors.get_Count();
}
int num = (int)this.progress;
int num2 = (num + 1) % this.colors.get_Count();
this.currentColor = Color.Lerp(this.colors.get_Item(num), this.colors.get_Item(num2), this.progress - (float)num);
return true;
}
}
}
|
using System;
namespace NeuralNetworksLab1.Models.Networks.ActivationFunctions
{
class LinearAF : IActivationFunction
{
public double Coefficient { get; set; }
public LinearAF()
{
Coefficient = 1.0;
}
public double GetOutputData(double input)
{
return Coefficient * input;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace neuron
{
//*****************************************LAYER*******************************************
public class Layer
{
int CountX = 0;
int index;
List<Neuron> neurons;
public List<double> Z;
public List<double> _sigma;
List<double> sigmaIn;
/// <summary>
/// 1.2.1 Create layer in neuron machine with N neurons and X enters in every neuron in layer
/// </summary>
/// <param name="CountOfNeuron">Количество нейронов в слое</param>
/// <param name="CountX">Количество входящих связей (нейронов предыдущего слоя)</param>
public Layer(int CountOfNeuron, int CountX)
{
neurons = new List<Neuron>();
CreateNeurons(CountOfNeuron, CountX);
}
/// <summary>
/// 1.2.2 Create N neurons with X entry in every neuron
/// </summary>
/// <param name="CountOfNeurons">Количество нейронов в слое</param>
/// <param name="CountX">Количество входящих связей (нейронов предыдущего слоя)</param>
public void CreateNeurons(int CountOfNeurons, int CountX)
{
for (int i = 0; i < CountOfNeurons; i++)
{
Console.WriteLine("Нейрон " + i);
Neuron n = new Neuron(CountX);
neurons.Add(n);
}
}
/// <summary>
/// 2.1.1 Layer work with entry data
/// </summary>
/// <param name="X">Входные данные в слой</param>
public void Work(List<double> X)
{
SendXAll(X);
}
/// <summary>
/// 2.1.2 Data sends for all neurons in layer
/// </summary>
/// <param name="X">Входные данные в слой</param>
void SendXAll(List<double> X)
{
Z = new List<double>();
int i = 0;
foreach (Neuron n in neurons)
{
Console.WriteLine("Нейрон "+ i++);
Z.Add(n.Work(X));
}
}
/// <summary>
/// 3.1.1 Teach OUTPUT layer
/// </summary>
/// <param name="T">Массив данных для обучения</param>
/// <param name="A">Скорость обучения нейросети</param>
public void TeachY(List<double> T, double A)
{
_sigma = new List<double>();
int i = 0;
foreach (Neuron n in neurons)
{
_sigma.Add(n.SigmaY(T[i++], A));
}
}
/// <summary>
///3.1.2 Teach HIDDEN layer
/// </summary>
/// <param name="SigmaK">Массив ошибок с предыдущего слоя</param>
/// <param name="A">Скорость обучения нейросети</param>
public void Teach(List<double> SigmaK, double A)
{
int i = 0;
foreach (Neuron n in neurons)
{
sigmaIn.Add(n.SigmaIn(SigmaK[i++], A));
}
}
/// <summary>
/// 3.1.3 Change weights in all neurons in layer
/// </summary>
/// <returns></returns>
public void ChangeWeights()
{
foreach (Neuron n in neurons)
{
n.ChangeWeights();
}
}
/// <summary>
/// Возвращает количество нейронов в слое
/// </summary>
/// <returns></returns>
public int CountOfNeuron()
{
return neurons.Count();
}
public Layer(int Index)
{
neurons = new List<Neuron>();
}
public void CreateNeuron(int Index, int CountX)
{
Neuron n = new Neuron(CountX);
neurons.Add(n);
}
}
//****************************************LAYER END****************************************
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Sunny.Lib;
namespace JobCommon
{
public class JobPropertyBag
{
public string ModulePath { get; set; }
public string ClassName { get; set; }
public Dictionary<string, object> Parameters { get; set; }
public static bool TryParse(string jsonStr, out JobPropertyBag propertyBag)
{
try
{
MemoryStream stream = new MemoryStream(System.Text.Encoding.Default.GetBytes(jsonStr));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JobPropertyBag));
propertyBag = (JobPropertyBag)serializer.ReadObject(stream);
return true;
}
catch (Exception exception)
{
Logger.LogError(exception);
propertyBag = null;
return false;
}
}
public override string ToString()
{
MemoryStream stream = new MemoryStream { Position = 0 };
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JobPropertyBag));
serializer.WriteObject(stream, this);
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
string strJson = reader.ReadToEnd();
return strJson;
}
}
}
|
using System.Threading.Tasks;
using Acme.Core.Models;
namespace Acme.Core.Repositories
{
public interface IAcquirerRepository
{
Task<Acquirer> GetByIdAsync(int id);
}
} |
using System;
namespace CfpExchange.Models
{
public class DownloadEventImageMessage
{
public Guid Id { get; set; }
public string ImageUrl { get; set; }
public bool HasDefaultImage()
{
return ImageUrl.EndsWith("noimage.svg", StringComparison.OrdinalIgnoreCase);
}
}
}
|
using Newtonsoft.Json;
/// <summary>
/// Scribble.rs ♯ data namespace
/// </summary>
namespace ScribblersSharp.Data
{
/// <summary>
/// A class that describes a sendable "kick-vote" game message
/// </summary>
[JsonObject(MemberSerialization.OptIn)]
internal class KickVoteSendGameMessageData : GameMessageData<string>, ISendGameMessageData
{
/// <summary>
/// Constructs a sendable "kick-vote" game message
/// </summary>
/// <param name="toKickPlayerID">To kick player ID</param>
public KickVoteSendGameMessageData(string toKickPlayerID) : base(Naming.GetSendGameMessageDataNameInKebabCase<KickVoteSendGameMessageData>(), toKickPlayerID)
{
// ...
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassStudent3
{
public class Student
{
public string firstname;
public string lastname;
public int age;
public string group;
}
class Program
{
static void Main(string[] args)
{
Student student1 = new Student();
Student student2 = new Student();
student1.group = "Group1";
student2.group = "Group2";
student1.firstname = "Nicolay";
student2.firstname = "Jhon";
Console.WriteLine("The first student's name is " + student1.firstname);
Console.WriteLine("The second student's name is " + student2.firstname);
Console.WriteLine(student2.group);
Console.WriteLine(student1.group);
Console.ReadKey();
}
}
}
|
namespace Plus.Communication.Packets.Outgoing.Inventory.Purse
{
internal class ActivityPointsComposer : MessageComposer
{
public int PixelsBalance { get; }
public int SeasonalCurrency { get; }
public int GotwPoints { get; }
public ActivityPointsComposer(int pixelsBalance, int seasonalCurrency, int gotwPoints)
: base(ServerPacketHeader.ActivityPointsMessageComposer)
{
PixelsBalance = pixelsBalance;
SeasonalCurrency = seasonalCurrency;
GotwPoints = gotwPoints;
}
public override void Compose(ServerPacket packet)
{
packet.WriteInteger(11); //Count
{
packet.WriteInteger(0); //Pixels
packet.WriteInteger(PixelsBalance);
packet.WriteInteger(1); //Snowflakes
packet.WriteInteger(16);
packet.WriteInteger(2); //Hearts
packet.WriteInteger(15);
packet.WriteInteger(3); //Gift points
packet.WriteInteger(14);
packet.WriteInteger(4); //Shells
packet.WriteInteger(13);
packet.WriteInteger(5); //Diamonds
packet.WriteInteger(SeasonalCurrency);
packet.WriteInteger(101); //Snowflakes
packet.WriteInteger(10);
packet.WriteInteger(102);
packet.WriteInteger(0);
packet.WriteInteger(103); //Stars
packet.WriteInteger(GotwPoints);
packet.WriteInteger(104); //Clouds
packet.WriteInteger(0);
packet.WriteInteger(105); //Diamonds
packet.WriteInteger(0);
}
}
}
} |
using System.Data.Entity.ModelConfiguration;
using Logs.Models;
namespace Logs.Data.Mappings
{
public class CommentMap : EntityTypeConfiguration<Comment>
{
public CommentMap()
{
// Primary Key
this.HasKey(t => t.CommentId);
// Properties
this.Property(t => t.UserId)
.HasMaxLength(128);
// Table & Column Mappings
this.ToTable("Comments");
this.Property(t => t.CommentId).HasColumnName("CommentId");
this.Property(t => t.Date).HasColumnName("Date");
this.Property(t => t.UserId).HasColumnName("UserId");
this.Property(t => t.EntryId).HasColumnName("EntryId");
this.Property(t => t.Content).HasColumnName("Content");
// Relationships
this.HasOptional(t => t.User)
.WithMany(t => t.Comments)
.HasForeignKey(d => d.UserId);
this.HasRequired(t => t.LogEntry)
.WithMany(t => t.Comments)
.HasForeignKey(d => d.EntryId);
}
}
}
|
using System.Configuration;
namespace Umbraco.Examine.Config
{
public sealed class IndexFieldCollection : ConfigurationElementCollection
{
#region Overridden methods to define collection
protected override ConfigurationElement CreateNewElement()
{
return new ConfigIndexField();
}
protected override object GetElementKey(ConfigurationElement element)
{
ConfigIndexField field = (ConfigIndexField)element;
return field.Name;
}
public override bool IsReadOnly()
{
return false;
}
#endregion
/// <summary>
/// Adds an index field to the collection
/// </summary>
/// <param name="field"></param>
public void Add(ConfigIndexField field)
{
BaseAdd(field, true);
}
/// <summary>
/// Default property for accessing an IndexField definition
/// </summary>
/// <value>Field Name</value>
/// <returns></returns>
public new ConfigIndexField this[string name]
{
get
{
return (ConfigIndexField)this.BaseGet(name);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sweepstakes
{
public static class UserInterface
{
public static string GetString(string typeOfString)
{
string response = "";
do
{
Console.WriteLine($"Enter {typeOfString}:");
response = Console.ReadLine();
Console.Clear();
if (response == "")
{
Console.WriteLine("You didn't enter anything! Try again.");
}
}
while (response == "");
return response;
}
public static string GetEmailAddress()
{
string emailAddress;
do
{
emailAddress = GetString("email address");
Console.Clear();
if (emailAddress.Contains("@") == false || emailAddress.Contains(".") == false)
{
Console.WriteLine("Not a valid email address! Try again.");
}
}
while (emailAddress.Contains("@") == false || emailAddress.Contains(".") == false);
return emailAddress;
}
public static void InitialDisplay()
{
Console.WriteLine("Welcome to your sweepstakes manager!");
}
public static string GetManagerChoice()
{
string managerChoice;
Console.WriteLine("Will your sweepstakes be maintained in a stack or a queue?");
do
{
managerChoice = GetString("(S) for stack or (Q) for queue");
Console.Clear();
managerChoice = managerChoice.ToLower();
if (managerChoice != "q" && managerChoice != "s")
{
Console.WriteLine("Didn't type Q or S! Try again.");
}
}
while (managerChoice != "q" && managerChoice != "s");
return managerChoice;
}
public static void FirmSearchOrAddMenu()
{
Console.WriteLine("Choose an option.");
Console.WriteLine("(1) Add a new sweepstakes.");
Console.WriteLine("(2) Search for a sweepstakes to view or edit.");
Console.WriteLine("(3) View all sweepstakes for the firm.");
Console.WriteLine("(4) Quit.");
}
public static void NotFoundMessage(string whatNotFound)
{
Console.WriteLine($"{whatNotFound} was not found.");
}
public static int GetNumberResponse(int min, int max)
{
int numberChoice = 0;
do
{
string response = Console.ReadLine();
Int32.TryParse(response, out numberChoice);
if (numberChoice < min || numberChoice > max)
{
Console.WriteLine("Not a valid choice! Try again.");
}
}
while (numberChoice < min || numberChoice > max);
return numberChoice;
}
public static void ShowAddSuccessMessage(string whatWasAdded)
{
Console.WriteLine($"New {whatWasAdded} successfully added!");
}
public static void FoundMessage(string whatFound)
{
Console.WriteLine($"{whatFound} was found");
}
public static void DisplayWinner(string winner)
{
Console.WriteLine($"{winner} has won!");
}
public static void SweepstakesFoundMenu(string sweepstakesName)
{
Console.WriteLine($"Sweepstake {sweepstakesName}");
Console.WriteLine("(1) Add a new contestant.");
Console.WriteLine("(2) Find a contestant to view their information.");
Console.WriteLine("(3) View sweepstake details.");
Console.WriteLine("(4) Choose the winner.");
Console.WriteLine("(5) View a list of all registered contestants.");
Console.WriteLine("(6) Back to search for/add new sweepstakes page.");
}
public static bool CheckWhetherNumberOrNot(string nameOrRegistrationNumber)
{
int possibleRegistrationNumber;
bool isNumeric = Int32.TryParse(nameOrRegistrationNumber, out possibleRegistrationNumber);
return isNumeric;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Leave.DataClients;
namespace Leave_Console
{
class ReportsDatabaseConnector
{
public static string getTable()
{
//try
//{
using (Leave.DataClients.SqlTableTracker test = new Leave.DataClients.SqlTableTracker(Leave.Modules.Holiday_Database_Connector.connection_string2, "Employees" + ", LeaveList"))
{
DataTable table = test.SelectSpecific("Employees.EmployeeName,LeaveType,LeavingDate,JoiningDate,Balance,DaysCount", "Employees.EmployeeID=LeaveList.EmployeeID" );
DataManager dm = new DataManager(table);
String columns = dm.ExtractColumns("\t") + "\n" + dm.ExtractData("\t");
return columns;
}
}
//}
}
}
|
using ServerPicker.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace ServerPicker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<ASServer> allEnvs = ASServer.GetAllServers();
AddLocalhostButton(allEnvs);
AddAlphaButtons(allEnvs);
AddStagingButtons(allEnvs);
AddProdButton(allEnvs);
resultLabel.Text = ASServer.GetCurrentEnv();
}
private void AddAlphaButtons(List<ASServer> allEnvs)
{
var al_boxes = allEnvs.Where(x => x.Name.Contains("AL_"));
var yAxis = 53;
var xAxis = 104;
foreach (var al in al_boxes)
{
CreateButton(xAxis, yAxis, al);
yAxis = yAxis + 45;
}
}
private void CreateButton(int xAxis, int yAxis, ASServer serverBox)
{
var button = new Button()
{
Text = serverBox.Name,
Location = new Point(xAxis, yAxis),
ForeColor = SystemColors.ActiveCaptionText,
Size = new Size(58, 29),
};
button.Click += new EventHandler(Apply_Click);
Controls.Add(button);
}
private void AddStagingButtons(List<ASServer> allEnvs)
{
var staging_boxes = allEnvs.Where(x => x.Name.Contains("STG_"));
var yAxis = 53;
var xAxis = 205;
foreach (var stg in staging_boxes)
{
CreateButton(xAxis, yAxis, stg);
yAxis = yAxis + 45;
}
}
private void AddLocalhostButton(List<ASServer> allEnvs)
{
var localhost = allEnvs.Find(x => x.Name.Equals("localhost"));
CreateButton(11, 53, localhost);
}
private void AddProdButton(List<ASServer> allEnvs)
{
var prod = allEnvs.Find(x => x.Name.Equals("Prod"));
CreateButton(300, 53, prod);
}
private void Apply_Click(object sender, EventArgs e)
{
CreateServerObject(((ButtonBase)sender).Text);
}
private void CreateServerObject(string serverName)
{
var server = new ASServer();
server.SetServerProperties(serverName);
resultLabel.Text = server.CurrentEnvironment;
}
private void OpenAsCom(object sender, LinkLabelLinkClickedEventArgs e)
{
OpenLink("http://www.alaskaair.com/");
}
private static void OpenLink(string link)
{
ProcessStartInfo sInfo = new ProcessStartInfo(link);
Process.Start(sInfo);
}
private void OpenMOW_Modal(object sender, LinkLabelLinkClickedEventArgs e)
{
if (Application.OpenForms["PopupForm"] as PopupForm != null)
Application.OpenForms["PopupForm"].Focus();
else
{
var form = new PopupForm();
form.Show();
}
}
private void OpenEasyBiz(object sender, LinkLabelLinkClickedEventArgs e)
{
OpenLink("http://easybiz.alaskaair.com");
}
}
}
|
using System;
using System.Collections.Generic;
namespace ELearning
{
public class Kurs
{
private String naziv;
private List<Lekcija> lekcije;
private List<Korisnik> upisani;
public Kurs(String naziv, List<Lekcija> lekcije, List<Korisnik> upisani)
{
this.naziv = naziv;
this.lekcije = lekcije;
this.upisani = upisani;
}
}
} |
//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.nopCommerce.com/License.aspx.
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
// See the License for the specific language governing rights and limitations under the License.
//
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
//
// Contributor(s): _______.
//------------------------------------------------------------------------------
using System;
namespace NopSolutions.NopCommerce.DataAccess.Content.Forums
{
/// <summary>
/// Acts as a base class for deriving custom forum provider
/// </summary>
[DBProviderSectionName("nopDataProviders/ForumProvider")]
public abstract partial class DBForumProvider : BaseDBProvider
{
#region Methods
/// <summary>
/// Deletes a forum group
/// </summary>
/// <param name="ForumGroupID">The forum group identifier</param>
public abstract void DeleteForumGroup(int ForumGroupID);
/// <summary>
/// Gets a forum group
/// </summary>
/// <param name="ForumGroupID">The forum group identifier</param>
/// <returns>Forum group</returns>
public abstract DBForumGroup GetForumGroupByID(int ForumGroupID);
/// <summary>
/// Gets all forum groups
/// </summary>
/// <returns>Forum groups</returns>
public abstract DBForumGroupCollection GetAllForumGroups();
/// <summary>
/// Inserts a forum group
/// </summary>
/// <param name="Name">The language name</param>
/// <param name="Description">The description</param>
/// <param name="DisplayOrder">The display order</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <param name="UpdatedOn">The date and time of instance update</param>
/// <returns>Forum group</returns>
public abstract DBForumGroup InsertForumGroup(string Name, string Description,
int DisplayOrder, DateTime CreatedOn, DateTime UpdatedOn);
/// <summary>
/// Updates the forum group
/// </summary>
/// <param name="ForumGroupID">The forum group identifier</param>
/// <param name="Name">The language name</param>
/// <param name="Description">The description</param>
/// <param name="DisplayOrder">The display order</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <param name="UpdatedOn">The date and time of instance update</param>
/// <returns>Forum group</returns>
public abstract DBForumGroup UpdateForumGroup(int ForumGroupID, string Name, string Description,
int DisplayOrder, DateTime CreatedOn, DateTime UpdatedOn);
/// <summary>
/// Deletes a forum
/// </summary>
/// <param name="ForumID">The forum identifier</param>
public abstract void DeleteForum(int ForumID);
/// <summary>
/// Gets a forum
/// </summary>
/// <param name="ForumID">The forum identifier</param>
/// <returns>Forum</returns>
public abstract DBForum GetForumByID(int ForumID);
/// <summary>
/// Gets forums by group identifier
/// </summary>
/// <param name="ForumGroupID">The forum group identifier</param>
/// <returns>Forums</returns>
public abstract DBForumCollection GetAllForumsByGroupID(int ForumGroupID);
/// <summary>
/// Inserts a forum
/// </summary>
/// <param name="ForumGroupID">The forum group identifier</param>
/// <param name="Name">The language name</param>
/// <param name="Description">The description</param>
/// <param name="NumTopics">The number of topics</param>
/// <param name="NumPosts">The number of posts</param>
/// <param name="LastTopicID">The last topic identifier</param>
/// <param name="LastPostID">The last post identifier</param>
/// <param name="LastPostUserID">The last post user identifier</param>
/// <param name="LastPostTime">The last post date and time</param>
/// <param name="DisplayOrder">The display order</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <param name="UpdatedOn">The date and time of instance update</param>
/// <returns>Forum</returns>
public abstract DBForum InsertForum(int ForumGroupID,
string Name, string Description,
int NumTopics, int NumPosts, int LastTopicID, int LastPostID,
int LastPostUserID, DateTime? LastPostTime, int DisplayOrder,
DateTime CreatedOn, DateTime UpdatedOn);
/// <summary>
/// Updates the forum
/// </summary>
/// <param name="ForumID">The forum identifier</param>
/// <param name="ForumGroupID">The forum group identifier</param>
/// <param name="Name">The language name</param>
/// <param name="Description">The description</param>
/// <param name="NumTopics">The number of topics</param>
/// <param name="NumPosts">The number of posts</param>
/// <param name="LastTopicID">The last topic identifier</param>
/// <param name="LastPostID">The last post identifier</param>
/// <param name="LastPostUserID">The last post user identifier</param>
/// <param name="LastPostTime">The last post date and time</param>
/// <param name="DisplayOrder">The display order</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <param name="UpdatedOn">The date and time of instance update</param>
/// <returns>Forum</returns>
public abstract DBForum UpdateForum(int ForumID, int ForumGroupID,
string Name, string Description,
int NumTopics, int NumPosts, int LastTopicID, int LastPostID,
int LastPostUserID, DateTime? LastPostTime, int DisplayOrder,
DateTime CreatedOn, DateTime UpdatedOn);
/// <summary>
/// Update forum stats
/// </summary>
/// <param name="ForumID">The forum identifier</param>
public abstract void UpdateForumStats(int ForumID);
/// <summary>
/// Deletes a topic
/// </summary>
/// <param name="ForumTopicID">The topic identifier</param>
public abstract void DeleteTopic(int ForumTopicID);
/// <summary>
/// Gets a topic
/// </summary>
/// <param name="ForumTopicID">The topic identifier</param>
/// <param name="IncreaseViews">The value indicating whether to increase topic views</param>
/// <returns>Topic</returns>
public abstract DBForumTopic GetTopicByID(int ForumTopicID, bool IncreaseViews);
/// <summary>
/// Gets all topics
/// </summary>
/// <param name="ForumID">The forum group identifier</param>
/// <param name="UserID">The user identifier</param>
/// <param name="Keywords">Keywords</param>
/// <param name="SearchPosts">A value indicating whether to search in posts</param>
/// <param name="PageSize">Page size</param>
/// <param name="PageIndex">Page index</param>
/// <param name="TotalRecords">Total records</param>
/// <returns>Topics</returns>
public abstract DBForumTopicCollection GetAllTopics(int ForumID, int UserID, string Keywords,
bool SearchPosts, int PageSize, int PageIndex, out int TotalRecords);
/// <summary>
/// Gets active topics
/// </summary>
/// <param name="ForumID">The forum group identifier</param>
/// <param name="TopicCount">Topic count. 0 if you want to get all topics</param>
/// <returns>Topics</returns>
public abstract DBForumTopicCollection GetActiveTopics(int ForumID, int TopicCount);
/// <summary>
/// Inserts a topic
/// </summary>
/// <param name="ForumID">The forum identifier</param>
/// <param name="UserID">The user identifier</param>
/// <param name="TopicTypeID">The topic type identifier</param>
/// <param name="Subject">The subject</param>
/// <param name="NumPosts">The number of posts</param>
/// <param name="Views">The number of views</param>
/// <param name="LastPostID">The last post identifier</param>
/// <param name="LastPostUserID">The last post user identifier</param>
/// <param name="LastPostTime">The last post date and time</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <param name="UpdatedOn">The date and time of instance update</param>
/// <returns>Topic</returns>
public abstract DBForumTopic InsertTopic(int ForumID, int UserID,
int TopicTypeID, string Subject,
int NumPosts, int Views, int LastPostID,
int LastPostUserID, DateTime? LastPostTime,
DateTime CreatedOn, DateTime UpdatedOn);
/// <summary>
/// Updates the topic
/// </summary>
/// <param name="ForumTopicID">The forum topic identifier</param>
/// <param name="ForumID">The forum identifier</param>
/// <param name="UserID">The user identifier</param>
/// <param name="TopicTypeID">The topic type identifier</param>
/// <param name="Subject">The subject</param>
/// <param name="NumPosts">The number of posts</param>
/// <param name="Views">The number of views</param>
/// <param name="LastPostID">The last post identifier</param>
/// <param name="LastPostUserID">The last post user identifier</param>
/// <param name="LastPostTime">The last post date and time</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <param name="UpdatedOn">The date and time of instance update</param>
/// <returns>Topic</returns>
public abstract DBForumTopic UpdateTopic(int ForumTopicID, int ForumID, int UserID,
int TopicTypeID, string Subject,
int NumPosts, int Views, int LastPostID,
int LastPostUserID, DateTime? LastPostTime,
DateTime CreatedOn, DateTime UpdatedOn);
/// <summary>
/// Deletes a post
/// </summary>
/// <param name="ForumPostID">The post identifier</param>
public abstract void DeletePost(int ForumPostID);
/// <summary>
/// Gets a post
/// </summary>
/// <param name="ForumPostID">The post identifier</param>
/// <returns>Post</returns>
public abstract DBForumPost GetPostByID(int ForumPostID);
/// <summary>
/// Gets all posts
/// </summary>
/// <param name="ForumTopicID">The forum topic identifier</param>
/// <param name="UserID">The user identifier</param>
/// <param name="Keywords">Keywords</param>
/// <param name="AscSort">Sort order</param>
/// <param name="PageSize">Page size</param>
/// <param name="PageIndex">Page index</param>
/// <param name="TotalRecords">Total records</param>
/// <returns>Posts</returns>
public abstract DBForumPostCollection GetAllPosts(int ForumTopicID, int UserID, string Keywords,
bool AscSort, int PageSize, int PageIndex, out int TotalRecords);
/// <summary>
/// Inserts a post
/// </summary>
/// <param name="ForumTopicID">The forum topic identifier</param>
/// <param name="UserID">The user identifier</param>
/// <param name="Text">The text</param>
/// <param name="IPAddress">The IP address</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <param name="UpdatedOn">The date and time of instance update</param>
/// <returns>Post</returns>
public abstract DBForumPost InsertPost(int ForumTopicID, int UserID,
string Text, string IPAddress, DateTime CreatedOn, DateTime UpdatedOn);
/// <summary>
/// Updates the post
/// </summary>
/// <param name="ForumPostID">The forum post identifier</param>
/// <param name="ForumTopicID">The forum topic identifier</param>
/// <param name="UserID">The user identifier</param>
/// <param name="Text">The text</param>
/// <param name="IPAddress">The IP address</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <param name="UpdatedOn">The date and time of instance update</param>
/// <returns>Post</returns>
public abstract DBForumPost UpdatePost(int ForumPostID, int ForumTopicID, int UserID,
string Text, string IPAddress, DateTime CreatedOn, DateTime UpdatedOn);
/// <summary>
/// Deletes a private message
/// </summary>
/// <param name="ForumPrivateMessageID">The private message identifier</param>
public abstract void DeletePrivateMessage(int ForumPrivateMessageID);
/// <summary>
/// Gets a private message
/// </summary>
/// <param name="ForumPrivateMessageID">The private message identifier</param>
/// <returns>Private message</returns>
public abstract DBPrivateMessage GetPrivateMessageByID(int ForumPrivateMessageID);
/// <summary>
/// Gets private messages
/// </summary>
/// <param name="FromUserID">The user identifier who sent the message</param>
/// <param name="ToUserID">The user identifier who should receive the message</param>
/// <param name="IsRead">A value indicating whether loaded messages are read. false - to load not read messages only, 1 to load read messages only, null to load all messages</param>
/// <param name="IsDeletedByAuthor">A value indicating whether loaded messages are deleted by author. false - messages are not deleted by author, null to load all messages</param>
/// <param name="IsDeletedByRecipient">A value indicating whether loaded messages are deleted by recipient. false - messages are not deleted by recipient, null to load all messages</param>
/// <param name="Keywords">Keywords</param>
/// <param name="PageSize">Page size</param>
/// <param name="PageIndex">Page index</param>
/// <param name="TotalRecords">Total records</param>
/// <returns>Private messages</returns>
public abstract DBPrivateMessageCollection GetAllPrivateMessages(int FromUserID, int ToUserID,
bool? IsRead, bool? IsDeletedByAuthor, bool? IsDeletedByRecipient,
string Keywords, int PageSize, int PageIndex, out int TotalRecords);
/// <summary>
/// Inserts a private message
/// </summary>
/// <param name="FromUserID">The user identifier who sent the message</param>
/// <param name="ToUserID">The user identifier who should receive the message</param>
/// <param name="Subject">The subject</param>
/// <param name="Text">The text</param>
/// <param name="IsRead">The value indivating whether message is read</param>
/// <param name="IsDeletedByAuthor">The value indivating whether message is deleted by author</param>
/// <param name="IsDeletedByRecipient">The value indivating whether message is deleted by recipient</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <returns>Private message</returns>
public abstract DBPrivateMessage InsertPrivateMessage(int FromUserID, int ToUserID,
string Subject, string Text, bool IsRead,
bool IsDeletedByAuthor, bool IsDeletedByRecipient, DateTime CreatedOn);
/// <summary>
/// Updates the private message
/// </summary>
/// <param name="PrivateMessageID">The private message identifier</param>
/// <param name="FromUserID">The user identifier who sent the message</param>
/// <param name="ToUserID">The user identifier who should receive the message</param>
/// <param name="Subject">The subject</param>
/// <param name="Text">The text</param>
/// <param name="IsRead">The value indivating whether message is read</param>
/// <param name="IsDeletedByAuthor">The value indivating whether message is deleted by author</param>
/// <param name="IsDeletedByRecipient">The value indivating whether message is deleted by recipient</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <returns>Private message</returns>
public abstract DBPrivateMessage UpdatePrivateMessage(int PrivateMessageID, int FromUserID, int ToUserID,
string Subject, string Text, bool IsRead,
bool IsDeletedByAuthor, bool IsDeletedByRecipient, DateTime CreatedOn);
/// <summary>
/// Deletes a forum subscription
/// </summary>
/// <param name="ForumSubscriptionID">The forum subscription identifier</param>
public abstract void DeleteSubscription(int ForumSubscriptionID);
/// <summary>
/// Gets a forum subscription
/// </summary>
/// <param name="ForumSubscriptionID">The forum subscription identifier</param>
/// <returns>Forum subscription</returns>
public abstract DBForumSubscription GetSubscriptionByID(int ForumSubscriptionID);
/// <summary>
/// Gets a forum subscription
/// </summary>
/// <param name="SubscriptionGUID">The forum subscription identifier</param>
/// <returns>Forum subscription</returns>
public abstract DBForumSubscription GetSubscriptionByGUID(int SubscriptionGUID);
/// <summary>
/// Gets forum subscriptions
/// </summary>
/// <param name="UserID">The user identifier</param>
/// <param name="ForumID">The forum identifier</param>
/// <param name="TopicID">The topic identifier</param>
/// <param name="PageSize">Page size</param>
/// <param name="PageIndex">Page index</param>
/// <param name="TotalRecords">Total records</param>
/// <returns>Forum subscriptions</returns>
public abstract DBForumSubscriptionCollection GetAllSubscriptions(int UserID, int ForumID,
int TopicID, int PageSize, int PageIndex, out int TotalRecords);
/// <summary>
/// Inserts a forum subscription
/// </summary>
/// <param name="SubscriptionGUID">The forum subscription identifier</param>
/// <param name="UserID">The user identifier</param>
/// <param name="ForumID">The forum identifier</param>
/// <param name="TopicID">The topic identifier</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <returns>Forum subscription</returns>
public abstract DBForumSubscription InsertSubscription(Guid SubscriptionGUID, int UserID,
int ForumID, int TopicID, DateTime CreatedOn);
/// <summary>
/// Updates the forum subscription
/// </summary>
/// <param name="SubscriptionID">The forum subscription identifier</param>
/// <param name="SubscriptionGUID">The forum subscription identifier</param>
/// <param name="UserID">The user identifier</param>
/// <param name="ForumID">The forum identifier</param>
/// <param name="TopicID">The topic identifier</param>
/// <param name="CreatedOn">The date and time of instance creation</param>
/// <returns>Forum subscription</returns>
public abstract DBForumSubscription UpdateSubscription(int SubscriptionID, Guid SubscriptionGUID, int UserID,
int ForumID, int TopicID, DateTime CreatedOn);
#endregion
}
}
|
using System;
using System.Linq;
namespace Physics
{
public class Program
{
static void Main()
{
// ILGpuTest.Run();
// The 'using' idiom guarantees proper resource cleanup.
// We request 30 UpdateFrame events per second, and unlimited
// RenderFrame events (as fast as the computer can handle).
using (var game = new AppWindow())
game.Run(30.0);
}
}
}
|
using System;
namespace MonoGame.Extended.Entities
{
//public class ComponentType : IEquatable<ComponentType>
//{
// public ComponentType(Type type, int id)
// {
// Type = type;
// Id = id;
// }
// public Type Type { get; }
// public int Id { get; }
// public bool Equals(ComponentType other)
// {
// if (ReferenceEquals(null, other)) return false;
// if (ReferenceEquals(this, other)) return true;
// return Id == other.Id;
// }
// public override bool Equals(object obj)
// {
// if (ReferenceEquals(null, obj)) return false;
// if (ReferenceEquals(this, obj)) return true;
// if (obj.GetType() != GetType()) return false;
// return Equals((ComponentType) obj);
// }
// public override int GetHashCode()
// {
// return Id;
// }
// public static bool operator ==(ComponentType left, ComponentType right)
// {
// return Equals(left, right);
// }
// public static bool operator !=(ComponentType left, ComponentType right)
// {
// return !Equals(left, right);
// }
//}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TechnologyEdit.cs" company="CGI">
// Copyright (c) CGI. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CGI.Reflex.Core;
using CGI.Reflex.Core.Attributes;
using CGI.Reflex.Core.Entities;
namespace CGI.Reflex.Web.Areas.Technologies.Models
{
public class TechnologyEdit
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[HiddenInput(DisplayValue = false)]
public int ParentId { get; set; }
[Required(ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "Required")]
[StringLength(50, ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "StringLength")]
[Display(ResourceType = typeof(CoreResources), Name = "Name")]
public string Name { get; set; }
[Display(ResourceType = typeof(CoreResources), Name = "Contact")]
[UIHint("Contact")]
public int? ContactId { get; set; }
[StringLength(255, ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "StringLength")]
[Display(ResourceType = typeof(CoreResources), Name = "Description")]
public string Description { get; set; }
public string ParentFullName { get; set; }
public bool HasChildren { get; set; }
[Display(ResourceType = typeof(CoreResources), Name = "EndOfSupport")]
public DateTime? EndOfSupport { get; set; }
[Display(ResourceType = typeof(CoreResources), Name = "TechnologyType")]
[UIHint("DomainValue")]
[DomainValue(DomainValueCategory.TechnologyType)]
public virtual int? TechnologyTypeId { get; set; }
public bool JustCreated { get; set; }
public int ApplicationCount { get; set; }
public int ServerCount { get; set; }
public string FormAction
{
get { return Id == 0 ? "Create" : "Edit"; }
}
}
} |
using McMaster.Extensions.CommandLineUtils;
using Serilog;
namespace FlipLeaf
{
internal class Program
{
private static int Main(string[] args)
{
// setup commandline app
var app = new CommandLineApplication(false);
app.HelpOption("-? | -h | --help");
var inputDir = app.Option("-i | --input", "Path to root site directory. By default current directory is used", CommandOptionType.SingleValue);
// default action : generate static site
app.OnExecute(async () =>
{
// load config
var site = inputDir.HasValue() ? new StaticSite(inputDir.Value()) : new StaticSite();
site.LoadConfiguration();
// todo apply command-line args to runtime
// configure content source
var contentSource = new Core.Inputs.FileInputSource(site.InputDirectory) { Exclude = new[] { "README.md" } };
// configure static source
var staticsource = new Core.Inputs.FileInputSource(site.GetFullRootPath("_static"));
// setup markdown processing pipeline
var parser = new Core.Text.MarkdigSpecifics.MarkdigParser();
parser.Use(new Core.Text.MarkdigSpecifics.WikiLinkExtension() { Extension = ".md" });
parser.Use(new Core.Text.MarkdigSpecifics.CustomLinkInlineRendererExtension(site));
site.AddPipeline(contentSource, new Core.Pipelines.TextTransformPipeline(
i => i.Extension == ".md",
// read
new Core.Text.ReadContentMiddleware(),
// prepare
new Core.Text.ITextMiddleware[] {
new Core.Text.YamlHeaderMiddleware(new Core.Text.YamlParser())
},
// transform
new Core.Text.ITextMiddleware[] {
new Core.Text.YamlHeaderMiddleware(new Core.Text.YamlParser()),
new Core.Text.LiquidMiddleware(new Core.Text.FluidLiquid.FluidParser(site)),
new Core.Text.MarkdownMiddleware(parser)
},
// write
new Core.Text.WriteContentMiddleware() { Extension = ".html" }
));
// setup static files pipeline
site.AddPipeline(staticsource, new Core.Pipelines.CopyPipeline());
// generate
await site.GenerateAsync();
});
return app.Execute(args);
}
}
}
|
using System;
using Profesion.Interface;
using Profesion.Implementacion;
namespace Profesiones.Negocio
{
public class Hospital
{
public Medico Medico { get; set; }
public MedicoPediatra MedicoPediatra { get; set; }
public MedicoCardiologo MedicoCardiologo { get; set; }
public MedicoTraumatologo MedicoTraumatologo { get; set; }
public string Contratar()
{
return "estoy contratando personal medico";
}
public string DetectarEnfermedad()
{
return Medico.Revisar() + "paciente";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Service.Layer;
using ViewModels.Layer;
namespace StoredVehicles.Controllers
{
public class HomeController : Controller
{
readonly IMarkaNaVoziloService ms;
public HomeController( IMarkaNaVoziloService ms)
{
this.ms = ms;
}
// public ActionResult Index()
// {
// List<VoziloViewModel> vozila = this.vs.GetVehicles().ToList();
// return View(vozila);
// }
public ActionResult About()
{
return View();
}
public ActionResult Contact()
{
return View();
}
public ActionResult MarkaNaVozilo()
{
List<MarkaNaVoziloViewModel> vozila = this.ms.GetModels();
return View(vozila);
}
}
} |
namespace Challenge_App.Data
{
public class ChallengeItemUsers
{
public int Id {get;set;}
public int ChallengeItemId {get;set;}
public ChallengeItem ChallengeItem {get;set;}
public int UserId {get;set;}
public User User {get;set;}
public bool Completed {get;set;}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.