本文整理汇总了C#中Common.List.Any方法的典型用法代码示例。如果您正苦于以下问题:C# List.Any方法的具体用法?C# List.Any怎么用?C# List.Any使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Common.List
的用法示例。
在下文中一共展示了List.Any方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ScheduleZoneDetailsViewModel
public ScheduleZoneDetailsViewModel(Schedule schedule, Organisation organisation)
{
Title = "Добавить новые зоны";
ScheduleZone = new List<ScheduleZone>();
Zones = new SortableObservableCollection<SelectationScheduleZoneViewModel>();
var organisationResult = OrganisationHelper.GetSingle(organisation.UID);
_doorUIDs = organisationResult != null ? organisationResult.DoorUIDs : new List<Guid>();
var gkDoors = GKManager.Doors.Where(x => _doorUIDs.Any(y => y == x.UID));
foreach (var door in gkDoors)
{
if (door.EnterZoneUID != Guid.Empty)
{
var enterZone = GKManager.SKDZones.FirstOrDefault(x => x.UID == door.EnterZoneUID);
if (enterZone != null && !Zones.Any(x => x.ZoneUID == enterZone.UID))
Zones.Add(new SelectationScheduleZoneViewModel(enterZone, schedule, door.UID));
}
if (door.ExitZoneUID != Guid.Empty)
{
var exitZone = GKManager.SKDZones.FirstOrDefault(x => x.UID == door.ExitZoneUID);
if (exitZone != null && !Zones.Any(x => x.ZoneUID == exitZone.UID))
Zones.Add(new SelectationScheduleZoneViewModel(exitZone, schedule, door.UID));
}
}
Zones = new ObservableCollection<SelectationScheduleZoneViewModel>(Zones.OrderBy(x => x.No)); //TODO:
SelectedZone = Zones.FirstOrDefault();
}
示例2: CalculateOrder
public static OrderCalculationResponse CalculateOrder(OrderCalculationRequest request, bool hasAutoOrder = false)
{
var result = new OrderCalculationResponse();
if (request.Items.Count() == 0) return result;
if (request.Address == null) request.Address = GlobalSettings.Company.Address;
if (request.ShipMethodID == 0) request.ShipMethodID = request.Configuration.DefaultShipMethodID;
var apirequest = new CalculateOrderRequest();
apirequest.WarehouseID = request.Configuration.WarehouseID;
apirequest.CurrencyCode = request.Configuration.CurrencyCode;
apirequest.PriceType = request.Configuration.PriceTypeID;
apirequest.ShipMethodID = request.ShipMethodID;
apirequest.ReturnShipMethods = request.ReturnShipMethods;
apirequest.City = request.Address.City;
apirequest.State = request.Address.State;
apirequest.Zip = request.Address.Zip;
apirequest.Country = request.Address.Country;
apirequest.Details = request.Items.Select(c => new OrderDetailRequest(c)).ToArray();
if(hasAutoOrder){
apirequest.OrderType = Common.Api.ExigoWebService.OrderType.AutoOrder;
}
var apiresponse = Exigo.WebService().CalculateOrder(apirequest);
result.Subtotal = apiresponse.SubTotal;
result.Shipping = apiresponse.ShippingTotal;
result.Tax = apiresponse.TaxTotal;
result.Discount = apiresponse.DiscountTotal;
result.Total = apiresponse.Total;
// Assemble the ship methods
var shipMethods = new List<ShipMethod>();
if (apiresponse.ShipMethods != null && apiresponse.ShipMethods.Length > 0)
{
foreach (var shipMethod in apiresponse.ShipMethods)
{
shipMethods.Add((ShipMethod)shipMethod);
}
// Ensure that at least one ship method is selected
var shipMethodID = (request.ShipMethodID != 0) ? request.ShipMethodID : request.Configuration.DefaultShipMethodID;
if (shipMethods.Any(c => c.ShipMethodID == (int)shipMethodID))
{
shipMethods.First(c => c.ShipMethodID == shipMethodID).Selected = true;
}
else
{
shipMethods.First().Selected = true;
}
}
result.ShipMethods = shipMethods.AsEnumerable();
return result;
}
示例3: GetByRefSysMenuIdAndSysRoleId
/// <summary>
/// 根据SysMenuId,获取所有角色菜单操作数据
/// </summary>
/// <param name="id">外键的主键</param>
/// <returns></returns>
public IQueryable<SysOperation> GetByRefSysMenuIdAndSysRoleId(SysEntities db, string id, List<string> sysRoleIds)
{
//兼容oracle
return
( from o in db.SysOperation
from m in db.SysMenuSysRoleSysOperation.Where(c => sysRoleIds.Any(a => a == c.SysRoleId) && c.SysMenuId == id && c.SysOperationId != null).Select(s => s.SysOperationId)
where o.Id == m
select o).Distinct().OrderBy(o=>o.Sort).AsQueryable()
;
}
示例4: GetAllUsers
public static List<User> GetAllUsers()
{
try
{
using (var context = DatabaseContext.Initialize())
{
var result = new List<User>();
foreach (var item in context.Users.Select(x => new { UID = x.UID, Name = x.Name, Login = x.Login }))
{
result.Add(new User
{
UID = item.UID,
Name = item.Name,
Login = item.Login
});
}
if (!result.Any())
{
var userpermissions = new List<UserPermission>();
User user = new User() { Name = "Adm", Login = "Adm", PasswordHash = HashHelper.GetHashFromString("") };
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.ViewConsumer });
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.ViewDevice });
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.EditConsumer });
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.EditDevice });
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.EditUser });
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.ViewUser });
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.ViewJournal });
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.ViewPlot });
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.ViewReport });
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.ViewTariff });
userpermissions.Add(new UserPermission { User = user, PermissionType = PermissionType.EditTariff });
user.UserPermissions = userpermissions;
context.Users.Add(user);
context.SaveChanges();
result.Add(user);
}
return result;
}
}
catch (Exception e)
{
MessageBoxService.ShowException(e);
return null;
}
}
示例5: OnGKObjectsStateChanged
void OnGKObjectsStateChanged(object obj)
{
alarms = new List<Alarm>();
foreach (var device in XManager.Devices)
{
if (!device.IsRealDevice)
//|| device.DriverType == XDriverType.GK || device.DriverType == XDriverType.KAU || device.DriverType == XDriverType.RSR2_KAU)
continue;
foreach (var stateClass in device.State.StateClasses)
{
switch (stateClass)
{
case XStateClass.Ignore:
alarms.Add(new Alarm(XAlarmType.Ignore, device));
break;
case XStateClass.Failure:
alarms.Add(new Alarm(XAlarmType.Failure, device));
break;
case XStateClass.On:
case XStateClass.TurningOn:
if (device.Driver.IsControlDevice)
{
if (!alarms.Any(x => x.AlarmType == XAlarmType.Turning && x.Device.UID == device.UID))
{
alarms.Add(new Alarm(XAlarmType.Turning, device));
}
}
break;
case XStateClass.Fire1:
alarms.Add(new Alarm(XAlarmType.Turning, device));
break;
case XStateClass.Fire2:
if (device.DriverType != XDriverType.AM1_T)
{
alarms.Add(new Alarm(XAlarmType.Turning, device));
}
break;
}
}
if (device.State.StateClasses.Contains(XStateClass.AutoOff) && device.Driver.IsControlDevice)
{
alarms.Add(new Alarm(XAlarmType.AutoOff, device));
}
if (device.State.StateClasses.Contains(XStateClass.Service)) // || device.DeviceState.IsRealMissmatch)
{
alarms.Add(new Alarm(XAlarmType.Service, device));
}
}
foreach (var zone in XManager.Zones)
{
foreach (var stateClass in zone.State.StateClasses)
{
switch (stateClass)
{
case XStateClass.Fire2:
alarms.Add(new Alarm(XAlarmType.Fire2, zone));
break;
case XStateClass.Fire1:
alarms.Add(new Alarm(XAlarmType.Fire1, zone));
break;
case XStateClass.Attention:
alarms.Add(new Alarm(XAlarmType.Attention, zone));
break;
case XStateClass.Ignore:
alarms.Add(new Alarm(XAlarmType.Ignore, zone));
break;
}
}
//if (zone.ZoneState.IsRealMissmatch)
//{
// alarms.Add(new Alarm(XAlarmType.Service, zone));
//}
}
foreach (var direction in XManager.Directions)
{
foreach (var stateClass in direction.State.StateClasses)
{
switch (stateClass)
{
case XStateClass.On:
case XStateClass.TurningOn:
alarms.Add(new Alarm(XAlarmType.NPTOn, direction));
break;
case XStateClass.Ignore:
alarms.Add(new Alarm(XAlarmType.Ignore, direction));
break;
}
}
//.........这里部分代码省略.........
示例6: doRequest
//TODO: lot of copy-pasta here. Refactor!
private string doRequest(string methodName, List<Tuple<string, string>> paramz = null)
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
WebException exc = null;
var delay = 0;
for (int i = 1; i <= RETRY_COUNT; i++)
{
var serverTimeDiff = new TimeSpan(-2, 0, 0);
var totalSeconds = (long)Math.Round((DateTime.Now - new DateTime(1970, 1, 1) + serverTimeDiff).TotalSeconds); //TODO: using DateTime.Now is not ideal, should use server time
totalSeconds += _timeOffset;
var parameters = new List<Tuple<string, string>>
{
//Must be sorted by key
new Tuple<string, string>("access_key", _config.AccessKey),
new Tuple<string, string>("created", totalSeconds.ToString()),
new Tuple<string, string>("method", methodName),
new Tuple<string, string>("secret_key", _config.SecretKey)
};
if (null != paramz && paramz.Any())
{
parameters.AddRange(paramz);
parameters = parameters.OrderBy(tuple => tuple.Item1).ToList();
}
//Finally add MD5 hash sign. It's out of sorting.
var sign = getMD5Hash(buildQueryString(parameters));
parameters.Add(new Tuple<string, string>("sign", sign));
var postData = buildQueryString(parameters);
delay += RETRY_DELAY;
try
{
var text = sendPostRequest(TRADING_API_URL, postData);
_logger.LastResponse = text;
return text;
}
catch (WebException we)
{
var text = String.Format("(ATTEMPT {0}/{1}) Web request failed with exception={2}; status={3}", i, RETRY_COUNT, we.Message, we.Status);
_logger.Warning(text);
exc = we;
Thread.Sleep(delay);
}
}
throw new Exception(String.Format("Web request failed {0} times in a row with error '{1}'. Giving up.", RETRY_COUNT, exc.Message));
}
示例7: GetObjectProviders
private List<ObjectProvider> GetObjectProviders()
{
if (this.InstallAdapter.MetadataTimestamp != this.InstallAdapter.RetrieveMetadataTimestamp())
{
List<ObjectProvider> MtoMAvailableProviders = new List<ObjectProvider>();
this.availableProviders = new List<ObjectProvider>();
RetrieveAllEntitiesRequest retrieveAll = new RetrieveAllEntitiesRequest();
RetrieveAllEntitiesResponse response = new RetrieveAllEntitiesResponse();
RetrieveEntityRequest entityRequest = new RetrieveEntityRequest();
this.PublishPreConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.StartRetrievingEntityMetadata));
response = this.InstallAdapter.OrganizationService.Execute(retrieveAll) as RetrieveAllEntitiesResponse;
foreach (EntityMetadata crmMetadata in response.EntityMetadata)
{
entityRequest.MetadataId = crmMetadata.MetadataId.Value;
entityRequest.EntityFilters = EntityFilters.Relationships;
RetrieveEntityResponse entityResponse = this.InstallAdapter.OrganizationService.Execute(entityRequest) as RetrieveEntityResponse;
if (entityResponse.EntityMetadata.DisplayName.LocalizedLabels.Count > 0 && !entityResponse.EntityMetadata.LogicalName.StartsWith("dynamics_deleted", StringComparison.OrdinalIgnoreCase) && entityResponse.EntityMetadata.IsCustomizable.Value)
{
this.availableProviders.Add(new DynamicObjectProvider() { Adapter = this.InstallAdapter, Id = crmMetadata.MetadataId.Value, DisplayName = entityResponse.EntityMetadata.DisplayName.LocalizedLabels[0].Label, Name = entityResponse.EntityMetadata.LogicalName });
}
List<ManyToManyRelationshipMetadata> entityMToMRelationships = (from meta in entityResponse.EntityMetadata.ManyToManyRelationships
where (meta.IsCustomRelationship.Value == true)
|| (meta.SecurityTypes == SecurityTypes.ParentChild && meta.IsCustomRelationship.Value == false)
select meta).ToList();
if (entityMToMRelationships.Count > 0)
{
foreach (ManyToManyRelationshipMetadata relation in entityMToMRelationships)
{
if (!MtoMAvailableProviders.Any(f => f.DisplayName == relation.SchemaName))
{
MtoMAvailableProviders.Add(new DynamicObjectProvider() { Adapter = this.InstallAdapter, Id = relation.MetadataId.Value, DisplayName = relation.SchemaName, Name = relation.SchemaName + ",Relationship" });
}
}
}
}
foreach (ObjectProvider relationObjectProvider in MtoMAvailableProviders)
{
this.availableProviders.Add(relationObjectProvider);
}
this.PublishPostConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.FinishedRetreivingEntityMetadata));
this.InstallAdapter.MetadataTimestamp = this.InstallAdapter.RetrieveMetadataTimestamp();
this.PublishPostConfigurationMessage(string.Format(CultureInfo.CurrentCulture, Resources.MetadataTimeStamp, this.InstallAdapter.MetadataTimestamp));
}
return this.availableProviders;
}
开发者ID:Microsoft,项目名称:Instance-Adapter-for-Microsoft-Dynamics-CRM,代码行数:51,代码来源:ConfigurationUtilities.cs
示例8: Apply
public Player Apply(TurnInfo info, IEnumerable<Player> queue)
{
var owner = queue.FirstOrDefault(p => p == info.Ball.Owner);
// We are not the owner.
if (owner == null) { return null; }
var ownerDistanceToGoal2 = (Field.EnemyGoal.Center - owner.Position).LengthSquared;
if(!info.Other.Players.Any(p => (p.Position - Field.EnemyGoal.Center).LengthSquared < ownerDistanceToGoal2))
{
if (ownerDistanceToGoal2 < 150 * 150)
{
owner.ActionShootGoal();
}
else
{
owner.ActionGo(Field.EnemyGoal.Center);
}
return owner;
}
var shotOnGoalTop = Field.EnemyGoal.Top - owner.Position;
var shotOnGoalCen = Field.EnemyGoal.Center - owner.Position;
var shotOnGoalBot = Field.EnemyGoal.Bottom - owner.Position;
var accuracy = Statistics.GetAccuracy(10, 0.75f);
var shotAngle = Theta.Create(shotOnGoalTop, shotOnGoalBot);
if (shotAngle > 2f * accuracy)
{
if (!info.Other.Players.Any(oppo => MightCatch(oppo.Position - owner.Position, shotOnGoalCen, 10, 0.75f)))
{
owner.ActionShootGoal();
return owner;
}
}
var passCandidates = info.Own.Players
.Where(p => p != owner && IsCandidate(owner, p, ownerDistanceToGoal2))
.OrderBy(p => (Field.EnemyGoal.Center - p.Position).LengthSquared)
.ToList();
if (!passCandidates.Any())
{
owner.ActionGo(Field.EnemyGoal.Center);
return owner;
}
var oppos = info.Other.Players.Where(p => p.Position.X > owner.Position.X).ToList();
foreach (var z in PassingZs)
{
foreach (var power in PassingPowers)
{
var safe = new List<Player>();
foreach (var candidate in passCandidates)
{
if (!info.Other.Players.Any(oppo => MightCatch(oppo.Position - owner.Position, candidate.Position - owner.Position, power, z)))
{
safe.Add(candidate);
}
}
if (safe.Any())
{
var target = safe.OrderBy(s => (s.Position - Field.EnemyGoal.Center).LengthSquared).FirstOrDefault();
owner.ActionShoot(target, PassingPower);
return owner;
}
}
}
// else run.
owner.ActionGo(Field.EnemyGoal.Center);
return owner;
}
示例9: suggestSellPrice
private double suggestSellPrice(List<Order> asks)
{
if (null == asks || !asks.Any())
{
return _sellOrderPrice > 0.0 ? _sellOrderPrice : _minSellPrice;
}
const int DEC_PLACES = 14;
double increment = 2.0 * _minPriceUpdate;
//Find first ASK price higher than minPrice
foreach (Order ask in asks)
{
//Don't consider own order
if (ask.SequenceNumber == _sellOrderId) //TODO: this is a pure guess. In case orderbook bid/ask cannot be matched with my order, use old method (price and amount equality)
{
continue;
}
if (ask.Price >= _minSellPrice)
{
double sellPrice = Math.Round(ask.Price - increment, DEC_PLACES);
//The difference is too small. Leave previous price to avoid server call
if (-1 != _sellOrderId && Math.Abs(sellPrice - _sellOrderPrice) < _minPriceUpdate)
{
log(String.Format("DEBUG: SELL price {0:0.00000} too similar, using previous", sellPrice));
return _sellOrderPrice;
}
if (sellPrice > _maxSellPrice)
{
return _maxSellPrice;
}
return sellPrice;
}
}
//Order book filled with junk. Use order before last, so we see it in chart
double price = asks.Last().Price - increment;
if (-1 != _sellOrderId && Math.Abs(price - _sellOrderPrice) < _minPriceUpdate)
{
return _sellOrderPrice;
}
return Math.Round(price, DEC_PLACES);
}
示例10: AddPassenger
/// <summary>
/// Adds the passenger.
/// </summary>
/// <param name="passengerPresenter">The passenger presenter.</param>
/// <returns>
/// The JSON Result
/// </returns>
public JsonResult AddPassenger(PassengerPresenter passengerPresenter)
{
if (passengerPresenter != null)
{
if (!string.IsNullOrEmpty(passengerPresenter.PersonIds) || (SessionData.Instance.SelectedPassengerIds != null && SessionData.Instance.SelectedPassengerIds.Count > 0))
{
var filteredPersonList = new List<Person>();
foreach (var persionId in SessionData.Instance.SelectedPassengerIds)
{
if (!SessionData.Instance.SelectedPersonIds.Contains(persionId))
{
SessionData.Instance.SelectedPersonIds.Add(persionId);
}
}
foreach (var personId in SessionData.Instance.SelectedPersonIds)
{
if (SessionData.Instance.PersonItemListResult != null)
{
foreach (var person in SessionData.Instance.PersonItemListResult)
{
if (person.PersonId == personId)
{
filteredPersonList.Add(person);
}
}
}
}
if (filteredPersonList.Count > 0)
{
if (SessionData.Instance.FilterPersonList != null)
{
foreach (var person in SessionData.Instance.FilterPersonList)
{
if (!filteredPersonList.Any(p => p.PersonId == person.PersonId))
{
filteredPersonList.Add(person);
}
}
}
}
SessionData.Instance.AssignFilterPersonResult(filteredPersonList);
}
}
return this.Json(true);
}
示例11: suggestPrice
private double suggestPrice(List<FiatAsk> asks, double minPrice, double maxPrice, int currentOrderId, double currentOrderPrice, double minPriceUpdate)
{
if (null == asks || !asks.Any())
{
return currentOrderPrice > 0.0 ? currentOrderPrice : minPrice;
}
const int DEC_PLACES = 14;
double increment = 2.0 * minPriceUpdate;
//Find first ASK price higher than minPrice
foreach (FiatAsk ask in asks)
{
//Don't consider own order
if (_config.AccessKey == ask.Account && ask.Sequence == currentOrderId)
{
continue;
}
if (ask.Price >= minPrice)
{
double sellPrice = Math.Round(ask.Price - increment, DEC_PLACES);
//The difference is too small. Leave previous price to avoid server call
if (-1 != currentOrderId && Math.Abs(sellPrice - currentOrderPrice) < minPriceUpdate)
{
log(String.Format("DEBUG: price {0:0.00000} too similar, using previous", sellPrice));
return currentOrderPrice;
}
if (sellPrice > maxPrice)
{
return maxPrice;
}
return sellPrice;
}
}
//Order book filled with junk. Use order before last, so we see it in chart
double price = asks.Last().Price - increment;
if (-1 != currentOrderId && Math.Abs(price - currentOrderPrice) < minPriceUpdate)
{
return currentOrderPrice;
}
if (price < minPrice)
{
return minPrice;
}
return Math.Round(price, DEC_PLACES);
}
示例12: sendPostRequest
private string sendPostRequest(string method, List<Tuple<string, string>> paramz = null)
{
string path = BASE_URL + method;
WebException exc = null;
for (int i = 1; i <= RETRY_COUNT; i++)
{
long nonce = DateTime.UtcNow.Ticks;
nonce += _nonceOffset;
string paramDict = "{" + String.Format("\"request\":\"/v1/{0}\",\"nonce\":\"{1}\"", method, nonce);
if (null != paramz && paramz.Any())
{
foreach (var param in paramz)
paramDict += "," + param.Item1 + ":" + param.Item2;
}
paramDict += "}";
string payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(paramDict));
var hmac = new HMACSHA384(Encoding.UTF8.GetBytes(_config.SecretKey));
byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
string hexHash = BitConverter.ToString(hash).Replace("-", "").ToLower();
var headers = new NameValueCollection
{
{"X-BFX-APIKEY", _config.AccessKey},
{"X-BFX-PAYLOAD", payload},
{"X-BFX-SIGNATURE", hexHash}
};
var request = (HttpWebRequest)WebRequest.Create(path);
request.KeepAlive = true;
request.Method = "POST";
if (null != _webProxy)
request.Proxy = _webProxy;
request.Headers.Add(headers);
byte[] byteArray = Encoding.UTF8.GetBytes(paramDict);
request.ContentLength = byteArray.Length;
using (var writer = request.GetRequestStream())
{
writer.Write(byteArray, 0, byteArray.Length);
}
try
{
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
var text = reader.ReadToEnd();
_logger.LastResponse = text;
return text;
}
}
}
}
catch (WebException we)
{
//Business errors act as 400-ProtocolError, so must be sorted out
if (we.Response != null)
{
using (var errorResponse = (HttpWebResponse)we.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string json = reader.ReadToEnd();
var error = Helpers.DeserializeJSON<ErrorResponse>(json);
if (!String.IsNullOrEmpty(error.message))
return json;
}
}
}
//Else real HTTP problem
var text = String.Format("(ATTEMPT {0}/{1}) Web request failed with exception={2}; status={3}", i, RETRY_COUNT, we.Message, we.Status);
_logger.Warning(text);
exc = we;
Thread.Sleep(RETRY_DELAY);
}
}
throw new Exception(String.Format("Web request failed {0} times in a row with error '{1}'. Giving up.", RETRY_COUNT, exc.Message));
}
示例13: suggestSellPrice
private double suggestSellPrice(List<MarketOrder> asks)
{
if (null == asks || !asks.Any())
{
return _sellOrderPrice > 0.0 ? _sellOrderPrice : _sellMinPrice;
}
const int DEC_PLACES = 14;
double increment = 2.0 * _minPriceUpdate;
//Find first ASK price higher than minPrice
foreach (MarketOrder ask in asks)
{
//Don't consider own order
if (ask.Amount.eq(_sellOrderAmount) && ask.Price.eq(_sellOrderPrice))
{
continue;
}
if (ask.Price >= _sellMinPrice)
{
double sellPrice = Math.Round(ask.Price - increment, DEC_PLACES);
//The difference is too small. Leave previous price to avoid server call
if (-1 != _sellOrderId && Math.Abs(sellPrice - _sellOrderPrice) < _minPriceUpdate)
{
log($"DEBUG: price {sellPrice:0.#####} too similar, using previous");
return _sellOrderPrice;
}
if (sellPrice > _sellMaxPrice)
{
return _sellMaxPrice;
}
return sellPrice;
}
}
//Order book filled with junk. Use order before last, so we see it in order book
double price = asks.Last().Price - increment;
if (-1 != _sellOrderId && Math.Abs(price - _sellOrderPrice) < _minPriceUpdate)
{
return _sellOrderPrice;
}
if (price < _sellMinPrice)
{
return _sellMinPrice;
}
return Math.Round(price, DEC_PLACES);
}
示例14: suggestBuyPrice
private double suggestBuyPrice(List<MarketOrder> bids)
{
if (null == bids || !bids.Any())
{
return _buyOrderPrice > 0.0 ? _buyOrderPrice : _buyMaxPrice;
}
const int DEC_PLACES = 14;
double increment = 2.0 * _minPriceUpdate;
//Find first BID price lower than maxPrice
foreach (MarketOrder bid in bids)
{
//Don't consider own order
if (bid.Amount.eq(_buyOrderAmount) && bid.Price.eq(_buyOrderPrice))
{
continue;
}
if (bid.Price <= _buyMaxPrice)
{
double buyPrice = Math.Round(bid.Price + increment, DEC_PLACES);
//The difference is too small. Leave previous buy price to avoid server call
if (-1 != _buyOrderId && Math.Abs(buyPrice - _buyOrderPrice) < _minPriceUpdate)
{
log($"DEBUG: price {buyPrice:0.#####} too similar, using previous");
return _buyOrderPrice;
}
if (buyPrice < _buyMinPrice)
{
return _buyMinPrice;
}
return buyPrice;
}
}
//Order book filled with junk. Use order before last, so we see it in order book
double price = bids.Last().Price + increment;
if (-1 != _buyOrderId && Math.Abs(price - _buyOrderPrice) < _minPriceUpdate)
{
return _buyOrderPrice;
}
if (price > _buyMaxPrice)
{
return _buyMaxPrice;
}
return Math.Round(price, DEC_PLACES);
}
示例15: CacheAssembly
/// <summary>
/// The cache assembly.
/// </summary>
/// <param name="activityAssemblyItems">
/// The activity assembly items.
/// </param>
public static void CacheAssembly(List<ActivityAssemblyItem> activityAssemblyItems, bool isFromServer = false)
{
if (activityAssemblyItems == null)
{
throw new ArgumentNullException("activityAssemblyItems");
}
if (activityAssemblyItems.Any(item => item == null))
{
throw new ArgumentNullException("activityAssemblyItems");
}
foreach (ActivityAssemblyItem assemblyItem in activityAssemblyItems)
{
// Skip cached item
if (assemblyItem.CachingStatus == CachingStatus.Latest)
{
continue;
}
// Check if a location is already in location catalog. If true, remove it first.
ActivityAssemblyItem cachedAssembly;
if (Utility.LoadCachedAssembly(ActivityAssemblyItems, assemblyItem.AssemblyName, out cachedAssembly))
{
ActivityAssemblyItems.Remove(cachedAssembly);
}
// Copy assemblies to local caching directory
string destFileName = Utility.CopyAssemblyToLocalCachingDirectory(assemblyItem.AssemblyName, assemblyItem.Location, false);
// break link to original location by resetting Location and AssemblyName.CodeBase
assemblyItem.Location = destFileName;
assemblyItem.AssemblyName.CodeBase = null;
assemblyItem.UpdateDateTime = DateTime.Now;
assemblyItem.CachingStatus = CachingStatus.Latest;
if (isFromServer)
{
var inspection = Utility.GetAssemblyInspectionService();
inspection.Inspect(destFileName);
assemblyItem.ActivityItems = inspection.SourceAssembly.ActivityItems;
assemblyItem.UserSelected = true;
assemblyItem.ActivityItems.ToList().ForEach(i =>
{
i.UserSelected = true;
i.Category = "Unassigned";
});
}
// Make ActivityItem read only. Note: ActivityItem's metadata can be edited only when imported.
foreach (var activityItem in assemblyItem.ActivityItems)
{
activityItem.IsReadOnly = true;
activityItem.CachingStatus = CachingStatus.Latest;
}
ActivityAssemblyItems.Add(assemblyItem);
}
}