本文整理汇总了C#中SortedDictionary.Any方法的典型用法代码示例。如果您正苦于以下问题:C# SortedDictionary.Any方法的具体用法?C# SortedDictionary.Any怎么用?C# SortedDictionary.Any使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SortedDictionary
的用法示例。
在下文中一共展示了SortedDictionary.Any方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Canonicalize
private static string Canonicalize(SortedDictionary<string, string> sortedParamMap)
{
if (!sortedParamMap.Any())
{
return string.Empty;
}
var sb = new StringBuilder(100);
foreach (var pair in sortedParamMap)
{
string key = pair.Key.ToLowerInvariant();
if (key.Equals("jsessionid") || key.Equals("phpsessid") || key.Equals("aspsessionid"))
{
continue;
}
if (sb.Length > 0)
{
sb.Append('&');
}
sb.Append(pair.Key.PercentEncodeRfc3986());
if (!string.IsNullOrEmpty(pair.Value))
{
sb.Append('=');
sb.Append(pair.Value.PercentEncodeRfc3986());
}
}
return sb.ToString();
}
示例2: ParseTaxRates
protected virtual SortedDictionary<decimal, decimal> ParseTaxRates(string taxRatesStr)
{
var taxRatesDictionary = new SortedDictionary<decimal, decimal>();
if (String.IsNullOrEmpty(taxRatesStr))
return taxRatesDictionary;
string[] lines = taxRatesStr.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (String.IsNullOrEmpty(line.Trim()))
continue;
string[] taxes = line.Split(new [] { ':' });
if (taxes.Length == 2)
{
try
{
decimal taxRate = decimal.Parse(taxes[0].Trim(), CultureInfo.InvariantCulture);
decimal taxValue = decimal.Parse(taxes[1].Trim(), CultureInfo.InvariantCulture);
taxRatesDictionary.Add(taxRate, taxValue);
}
catch (Exception exc)
{
Debug.WriteLine(exc.ToString());
}
}
}
//add at least one tax rate (0%)
if (!taxRatesDictionary.Any())
taxRatesDictionary.Add(decimal.Zero, decimal.Zero);
return taxRatesDictionary;
}
示例3: KwayMerge
private static void KwayMerge(IEnumerable<string> chunkFilePaths, string resultFilePath)
{
var chunkReaders = chunkFilePaths
.Select(path => new StreamReader(path))
.Where(chunkReader => !chunkReader.EndOfStream)
.ToList();
var sortedDict = new SortedDictionary<string, TextReader>();
chunkReaders.ForEach(chunkReader => sortedDict.Add(chunkReader.ReadLine(), chunkReader));
using (var resultWriter = new StreamWriter(resultFilePath, false))
while (sortedDict.Any())
{
var line = sortedDict.Keys.First();
var chunkReader = sortedDict[line];
sortedDict.Remove(line);
resultWriter.WriteLine(line);
var nextLine = chunkReader.ReadLine();
if (nextLine != null)
{
sortedDict.Add(nextLine, chunkReader);
}
else
{
chunkReader.Dispose();
}
}
}
示例4: DoPostRequest
public static string DoPostRequest(string Url, SortedDictionary<string,string> paramData, Encoding dataEncode)
{
string ret = string.Empty;
Stream stream = null;
HttpWebResponse response = null;
StreamReader sr = null;
try
{
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(Url);
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
if (paramData.Any())
{
StringBuilder parms = new StringBuilder();
foreach (var item in paramData)
{
parms.Append(String.Format("{0}={1}&", item.Key, item.Value));
}
//LogHelper.Write(CommonLogger.HuiFu, LogLevel.Trace,"请求参数:"+parms.ToString());
byte[] byteArray = dataEncode.GetBytes(parms.ToString().Substring(0, parms.ToString().Length - 1));
webReq.ContentLength = byteArray.Length;
stream = webReq.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream.Close();
}
response = (HttpWebResponse)webReq.GetResponse();
sr = new StreamReader(response.GetResponseStream(), dataEncode);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
}
catch (Exception ex)
{
LogHelper.Write(CommonLogger.Application, LogLevel.Error, ex);
if (stream != null)
{
stream.Close();
}
if (sr != null)
{
sr.Close();
}
if (response != null)
{
response.Close();
}
throw ex;
}
return ret;
}
示例5: CreateOrUpdateAssemblies
private SortedDictionary<Tuple<SemanticVersion, string>, DllReference> CreateOrUpdateAssemblies(IEnumerable<string> dlls)
{
_assemblies = new SortedDictionary<Tuple<SemanticVersion, string>, DllReference>();
if (_useCache)
_serializer.Load(ref _conflictingAssemblies, ref _assemblies);
//Ugly Performance...
var notAlreadyCompute = dlls
.Where(dll => !_assemblies.Any(_ => dll.Equals(_.Value.Path)))
.ToList();
foreach (var dll in notAlreadyCompute)
{
CreateOrUpdateAssembly(dll);
}
if (_useCache)
_serializer.Save(_conflictingAssemblies, _assemblies);
return Assemblies;
}
示例6: HicWorker
//.........这里部分代码省略.........
case HCI.Event.HCI_Number_Of_Completed_Packets_EV:
for (byte index = 0, ptr = 3; index < buffer[2]; index++, ptr += 4)
{
OnCompletedCount(buffer[ptr], (byte) (buffer[ptr + 1] | 0x20),
(ushort) (buffer[ptr + 2] | buffer[ptr + 3] << 8));
}
break;
#endregion
#region HCI_Remote_Name_Request_Complete_EV
case HCI.Event.HCI_Remote_Name_Request_Complete_EV:
bd = string.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", buffer[8], buffer[7],
buffer[6], buffer[5], buffer[4], buffer[3]);
var nm = new StringBuilder();
// extract product name
for (var index = 9; index < buffer.Length; index++)
{
if (buffer[index] > 0) nm.Append((char) buffer[index]);
else break;
}
var name = nm.ToString();
Log.InfoFormat("-- Remote Name : {0} - {1}", bd, name);
// extract MAC address
Buffer.BlockCopy(buffer, 3, bdAddr, 0, 6);
if (hci.SupportedNames.Any(n => name.StartsWith(n))
|| hci.SupportedNames.Any(n => name == n))
{
nameList.Add(bd, nm.ToString());
// the code below is just cut-paste from "case HCI.Event.HCI_Connection_Complete_EV"
// just some adjustments made in the buffer variables
if (!nameList.Any())
break;
connection = Add(bdHandle[0], (byte) (bdHandle[1] | 0x20), nameList[bd]);
//using there the handles saved earlier
// signal L2CAP task to continue
_waitForConnectionComplete.Set();
#region Fake DS3 workaround
if (GlobalConfiguration.Instance.UseDs3CounterfeitWorkarounds &&
!hci.GenuineMacAddresses.Any(m => bd.StartsWith(m)))
{
connection.IsFake = true;
Log.Warn("-- Fake DualShock 3 found. Workaround applied");
}
else
{
connection.IsFake = false;
Log.Info("-- Genuine Sony DualShock 3 found");
}
#endregion
示例7: ToNikePlusActicity
/// <summary>
/// Maps <see cref="MSHealthAPI.MSHealthActivity"/> instance to <see cref="NikePlusAPI.NikePlusActivity"/> instance.
/// </summary>
/// <param name="activityIn"><see cref="MSHealthAPI.MSHealthActivity"/> instance to map.</param>
/// <returns><see cref="NikePlusAPI.NikePlusActivity"/> instance.</returns>
public static NikePlusActivity ToNikePlusActicity(this MSHealthActivity activityIn)
{
NikePlusActivity loActivityOut = null;
if (activityIn != null)
{
loActivityOut = new NikePlusActivity();
// Distance
double ldDistance = 0;
if (activityIn.SplitDistance != null &&
activityIn.DistanceSummary != null &&
activityIn.DistanceSummary.TotalDistance != null)
{
ldDistance = activityIn.DistanceSummary.TotalDistance.Value / activityIn.SplitDistance.Value;
if (activityIn.SplitDistance.Value == MSHealthActivity.SPLIT_DISTANCE_MILE)
ldDistance = ldDistance * 1.609344; //1609.344;
if (loActivityOut.MetricSummary == null)
loActivityOut.MetricSummary = new NikePlusMetricSummary();
loActivityOut.MetricSummary.Distance = ldDistance;
}
// Duration
if (activityIn.Duration != null)
{
loActivityOut.Duration = activityIn.Duration.Value.TotalMilliseconds;
if (loActivityOut.MetricSummary == null)
loActivityOut.MetricSummary = new NikePlusMetricSummary();
loActivityOut.MetricSummary.Duration = activityIn.Duration;
}
// Start Time
if (activityIn.StartTime != null &&
activityIn.StartTime.HasValue)
loActivityOut.StartTime = activityIn.StartTime.Value;
// Status
loActivityOut.Status = NikePlusActivityStatus.COMPLETE;
// Type
switch (activityIn.Type)
{
case MSHealthActivityType.Run:
loActivityOut.Type = NikePlusActivityType.RUN;
break;
case MSHealthActivityType.Bike:
loActivityOut.Type = NikePlusActivityType.CYCLE;
break;
case MSHealthActivityType.Sleep:
loActivityOut.Type = NikePlusActivityType.SLEEPING;
break;
default:
loActivityOut.Type = NikePlusActivityType.OTHER;
break;
}
// Calories
if (activityIn.CaloriesBurnedSummary != null &&
activityIn.CaloriesBurnedSummary.TotalCalories != null)
{
if (loActivityOut.MetricSummary == null)
loActivityOut.MetricSummary = new NikePlusMetricSummary();
loActivityOut.MetricSummary.Calories = activityIn.CaloriesBurnedSummary.TotalCalories;
}
// Device
loActivityOut.DeviceType = NikePlusDeviceType.WATCH; // Nike doesn't recognize MSBand as valid device, so, set as WATCH
// Get valid MapPoints (with Location Latitude and Longitude)
IEnumerable<MSHealthMapPoint> loMapPoints = null;
if (activityIn.MapPoints != null &&
activityIn.MapPoints.Any())
{
loMapPoints = activityIn.MapPoints
.Where(loMP => loMP.IsPaused != null &&
!loMP.IsPaused.Value &&
loMP.SecondsSinceStart != null)
.OrderBy(loMP => loMP.Ordinal);
}
// Metrics
List<NikePlusMetric> loMetrics = new List<NikePlusMetric>();
NikePlusMetric loMetricDistance = new NikePlusMetric() { Type = NikePlusMetricType.DISTANCE };
NikePlusMetric loMetricHeartRate = new NikePlusMetric() { Type = NikePlusMetricType.HEARTRATE };
NikePlusMetric loMetricSpeed = new NikePlusMetric { Type = NikePlusMetricType.SPEED };
NikePlusMetric loMetricCalories = new NikePlusMetric { Type = NikePlusMetricType.CALORIES };
SortedDictionary<float, float> loDistanceToDurationNodes = new SortedDictionary<float, float>();
SortedDictionary<float, float> loHeartRateToDurationNodes = new SortedDictionary<float, float>();
SortedDictionary<float, float> loSpeedToDurationNodes = new SortedDictionary<float, float>();
SortedDictionary<float, float> loCaloriesToDurationNodes = new SortedDictionary<float, float>();
SortedDictionary<float, float> loDurationToDistanceNodes = new SortedDictionary<float, float>();
double ldTotalDistance = 0;
float lfTotalSeconds = 0;
if (loMapPoints != null &&
loMapPoints.Any())
{
foreach (MSHealthMapPoint loMapPoint in loMapPoints)
{
// Location
if (loMapPoint.Location != null)
{
// Latitude/Longitude
if (loMapPoint.Location.Latitude != null &&
loMapPoint.Location.Longitude != null)
{
//.........这里部分代码省略.........
示例8: searchPathOnMap
/// <summary>
/// Searches a path on a given map. The map data is altered in the process and a path is set on it.
/// </summary>
/// <param name="whatMap">The map to search a path on</param>
/// <returns>Whether a path could be found</returns>
public static SearchResult searchPathOnMap(WorldMap whatMap)
{
if (whatMap.goal == null || whatMap.start == null)
throw new ArgumentException("The provided map does either not have a start or a goal.", "whatMap");
SearchResult currentResult = SearchResult.None;
//Initialize open list
SortedDictionary<int, List<MapNode>> openList = new SortedDictionary<int, List<MapNode>>();
MapNode cache = whatMap.actualMap[whatMap.start.Item1][whatMap.start.Item2][whatMap.start.Item3];
cache.currentShortestPathToNode = 0;
openList.Add(cache.possibleDistanceToGoal, new List<MapNode>() { cache });
//Very simple test whether it makes sense to search the map at all
if (cache.currentStatus == MapNode.Status.isClosed)
{
currentResult |= SearchResult.MapHasAlreadyBeenSearched;
cache = whatMap.actualMap[whatMap.goal.Item1][whatMap.goal.Item2][whatMap.goal.Item3];
for (int i = 0; i < CIRCLE_TIMEOUT && cache != null && cache != whatMap.start; i++)
{
cache = cache.currentPredesessorNode;
}
if (cache != null)
{
if (cache == whatMap.start)
currentResult |= SearchResult.FoundPath;
else
throw new Exception("Map has been altered to contain a circle as a path");
}
}
else
{
//The actual searching. Take the node with the possibly least remaining distance ( estimated ) and expand it
while (openList.Any())
{
cache = openList.First().Value.First();
//remove it from the open list and possibly the entire entry list if empty
openList[cache.possibleDistanceToGoal].Remove(cache);
if (!openList[cache.possibleDistanceToGoal].Any())
openList.Remove(cache.possibleDistanceToGoal);
//Have we found the goal?
if (cache == whatMap.goal)
{
currentResult = SearchResult.FoundPath;
break;
}
cache.currentStatus |= MapNode.Status.isClosed;
expandNode(cache, openList, whatMap);
}
//Create the path information on the map data ( This is an extra list for simplicity, the main data has been altered already above )
LinkedList<BlockInfo> path = new LinkedList<BlockInfo>();
if (currentResult.HasFlag(SearchResult.FoundPath))
{
cache = whatMap.actualMap[whatMap.goal.Item1][whatMap.goal.Item2][whatMap.goal.Item3];
while (cache.currentPredesessorNode != null)
{
path.AddFirst(new BlockInfo(cache.x, cache.y, cache.z, cache.currentStatus));
cache = cache.currentPredesessorNode;
}
//Add the start aswell even though its predecessor is null ( obviously )
path.AddFirst(new BlockInfo(cache.x, cache.y, cache.z, cache.currentStatus));
}
whatMap.path = path;
}
return currentResult;
}
示例9: DataInitialization
/// <summary>
/// 传入数据初始化
/// </summary>
private void DataInitialization()
{
Sorted = YunUtils.GetRequest(false);
if (!Sorted.Any())
{
Sorted = YunUtils.GetRequest(true);
}
// _urlLog.Trace(TopUtils.CreateLinkstring(Sorted.ToDictionary(e => e.Key, e => e.Value)));
}
示例10: HicWorker
//.........这里部分代码省略.........
{
Transfered = HCI_Write_Extended_Inquiry_Response();
}
if (Command == HCI.Command.HCI_Write_Extended_Inquiry_Response && Buffer[5] == 0)
{
Transfered = HCI_Write_Local_Name();
}
if (Command == HCI.Command.HCI_Write_Local_Name && Buffer[5] == 0)
{
Transfered = HCI_Write_Scan_Enable();
}
if (Command == HCI.Command.HCI_Write_Scan_Enable && Buffer[5] == 0)
{
Initialised = true;
}
break;
case HCI.Event.HCI_Connection_Request_EV:
for (var i = 0; i < 6; i++) BD_Addr[i] = Buffer[i + 2];
Transfered = HCI_Delete_Stored_Link_Key(BD_Addr);
Transfered = HCI_Remote_Name_Request(BD_Addr);
break;
case HCI.Event.HCI_Connection_Complete_EV:
bd = string.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", Buffer[10],
Buffer[9], Buffer[8], Buffer[7], Buffer[6], Buffer[5]);
if (!nameList.Any())
break;
Connection = Add(Buffer[3], (byte)(Buffer[4] | 0x20), nameList[bd]);
#region Fake DS3 workaround
if (!hci.GenuineMacAddresses.Any(m => bd.StartsWith(m)))
{
Connection.IsFake = true;
Log.Warn("-- Fake DualShock 3 found. Workaround applied");
}
else
{
Connection.IsFake = false;
Log.Info("-- Genuine Sony DualShock 3 found");
}
#endregion
Connection.RemoteName = nameList[bd];
nameList.Remove(bd);
Connection.BdAddress = new[] { Buffer[10], Buffer[9], Buffer[8], Buffer[7], Buffer[6], Buffer[5] };
break;
case HCI.Event.HCI_Disconnection_Complete_EV:
Remove(Buffer[3], (byte)(Buffer[4] | 0x20));
break;
case HCI.Event.HCI_Number_Of_Completed_Packets_EV:
for (byte Index = 0, Ptr = 3; Index < Buffer[2]; Index++, Ptr += 4)
示例11: UpdateOrderTotals
//.........这里部分代码省略.........
{
var shippingOption = shippingOptionsResponse.ShippingOptions.FirstOrDefault(option => updatedOrder.ShippingMethod.Contains(option.Name));
if (shippingOption != null)
shippingTotal = shippingOption.Rate;
else
updateOrderParameters.Warnings.Add(string.Format("Shipping method {0} could not be loaded", updatedOrder.ShippingMethod));
}
else
updateOrderParameters.Warnings.AddRange(shippingOptionsResponse.Errors);
}
}
else
{
//before updating order was without shipping
if (_shippingSettings.AllowPickUpInStore)
{
//try to get the cheapest pickup point
var pickupPointsResponse = _shippingService.GetPickupPoints(updatedOrder.BillingAddress, null, _storeContext.CurrentStore.Id);
if (pickupPointsResponse.Success)
{
updateOrderParameters.PickupPoint = pickupPointsResponse.PickupPoints.OrderBy(point => point.PickupFee).First();
shippingTotal = updateOrderParameters.PickupPoint.PickupFee;
}
else
updateOrderParameters.Warnings.AddRange(pickupPointsResponse.Errors);
}
else
updateOrderParameters.Warnings.Add("Pick up in store is not available");
if (updateOrderParameters.PickupPoint == null)
{
//or try to get the cheapest shipping option for the shipping to the customer address
var shippingRateComputationMethods = _shippingService.LoadActiveShippingRateComputationMethods(_storeContext.CurrentStore.Id);
if (shippingRateComputationMethods.Any())
{
var shippingOptionsResponse = _shippingService.GetShippingOptions(restoredCart, customer.ShippingAddress, null, _storeContext.CurrentStore.Id);
if (shippingOptionsResponse.Success)
{
var shippingOption = shippingOptionsResponse.ShippingOptions.OrderBy(option => option.Rate).First();
updatedOrder.ShippingRateComputationMethodSystemName = shippingOption.ShippingRateComputationMethodSystemName;
updatedOrder.ShippingMethod = shippingOption.Name;
updatedOrder.ShippingAddress = (Address)customer.ShippingAddress.Clone();
shippingTotal = shippingOption.Rate;
}
else
updateOrderParameters.Warnings.AddRange(shippingOptionsResponse.Errors);
}
else
updateOrderParameters.Warnings.Add("Shipping rate computation method could not be loaded");
}
}
//additional shipping charge
shippingTotal += restoredCart.Where(item => item.IsShipEnabled && !item.IsFreeShipping).Sum(item => item.Product.AdditionalShippingCharge);
//shipping discounts
List<Discount> shippingTotalDiscounts;
shippingTotal -= GetShippingDiscount(customer, shippingTotal, out shippingTotalDiscounts);
if (shippingTotal < decimal.Zero)
shippingTotal = decimal.Zero;
shippingTotalExclTax = _taxService.GetShippingPrice(shippingTotal, false, customer);
shippingTotalInclTax = _taxService.GetShippingPrice(shippingTotal, true, customer, out shippingTaxRate);
//rounding
if (_shoppingCartSettings.RoundPricesDuringCalculation)
示例12: GetTaxTotal
//.........这里部分代码省略.........
var customer = cart.GetCustomer();
string paymentMethodSystemName = "";
if (customer != null)
{
paymentMethodSystemName = customer.GetAttribute<string>(
SystemCustomerAttributeNames.SelectedPaymentMethod,
_genericAttributeService,
_storeContext.CurrentStore.Id);
}
//order sub total (items + checkout attributes)
decimal subTotalTaxTotal = decimal.Zero;
decimal orderSubTotalDiscountAmount;
List<Discount> orderSubTotalAppliedDiscounts;
decimal subTotalWithoutDiscountBase;
decimal subTotalWithDiscountBase;
SortedDictionary<decimal, decimal> orderSubTotalTaxRates;
GetShoppingCartSubTotal(cart, false,
out orderSubTotalDiscountAmount, out orderSubTotalAppliedDiscounts,
out subTotalWithoutDiscountBase, out subTotalWithDiscountBase,
out orderSubTotalTaxRates);
foreach (KeyValuePair<decimal, decimal> kvp in orderSubTotalTaxRates)
{
decimal taxRate = kvp.Key;
decimal taxValue = kvp.Value;
subTotalTaxTotal += taxValue;
if (taxRate > decimal.Zero && taxValue > decimal.Zero)
{
if (!taxRates.ContainsKey(taxRate))
taxRates.Add(taxRate, taxValue);
else
taxRates[taxRate] = taxRates[taxRate] + taxValue;
}
}
//shipping
decimal shippingTax = decimal.Zero;
if (_taxSettings.ShippingIsTaxable)
{
decimal taxRate;
decimal? shippingExclTax = GetShoppingCartShippingTotal(cart, false, out taxRate);
decimal? shippingInclTax = GetShoppingCartShippingTotal(cart, true, out taxRate);
if (shippingExclTax.HasValue && shippingInclTax.HasValue)
{
shippingTax = shippingInclTax.Value - shippingExclTax.Value;
//ensure that tax is equal or greater than zero
if (shippingTax < decimal.Zero)
shippingTax = decimal.Zero;
//tax rates
if (taxRate > decimal.Zero && shippingTax > decimal.Zero)
{
if (!taxRates.ContainsKey(taxRate))
taxRates.Add(taxRate, shippingTax);
else
taxRates[taxRate] = taxRates[taxRate] + shippingTax;
}
}
}
//payment method additional fee
decimal paymentMethodAdditionalFeeTax = decimal.Zero;
if (usePaymentMethodAdditionalFee && _taxSettings.PaymentMethodAdditionalFeeIsTaxable)
{
decimal taxRate;
decimal paymentMethodAdditionalFee = _paymentService.GetAdditionalHandlingFee(cart, paymentMethodSystemName);
decimal paymentMethodAdditionalFeeExclTax = _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, false, customer, out taxRate);
decimal paymentMethodAdditionalFeeInclTax = _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, true, customer, out taxRate);
paymentMethodAdditionalFeeTax = paymentMethodAdditionalFeeInclTax - paymentMethodAdditionalFeeExclTax;
//ensure that tax is equal or greater than zero
if (paymentMethodAdditionalFeeTax < decimal.Zero)
paymentMethodAdditionalFeeTax = decimal.Zero;
//tax rates
if (taxRate > decimal.Zero && paymentMethodAdditionalFeeTax > decimal.Zero)
{
if (!taxRates.ContainsKey(taxRate))
taxRates.Add(taxRate, paymentMethodAdditionalFeeTax);
else
taxRates[taxRate] = taxRates[taxRate] + paymentMethodAdditionalFeeTax;
}
}
//add at least one tax rate (0%)
if (!taxRates.Any())
taxRates.Add(decimal.Zero, decimal.Zero);
//summarize taxes
decimal taxTotal = subTotalTaxTotal + shippingTax + paymentMethodAdditionalFeeTax;
//ensure that tax is equal or greater than zero
if (taxTotal < decimal.Zero)
taxTotal = decimal.Zero;
//round tax
if (_shoppingCartSettings.RoundPricesDuringCalculation)
taxTotal = RoundingHelper.RoundPrice(taxTotal);
return taxTotal;
}
示例13: ProductListToHtmlTable
//.........这里部分代码省略.........
cusShipTotal = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false);
//payment method additional fee
var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
cusPaymentMethodAdditionalFee = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, language, false);
}
//shipping
bool displayShipping = order.ShippingStatus != ShippingStatus.ShippingNotRequired;
//payment method fee
bool displayPaymentMethodFee = order.PaymentMethodAdditionalFeeExclTax > decimal.Zero;
//tax
bool displayTax = true;
bool displayTaxRates = true;
if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
{
displayTax = false;
displayTaxRates = false;
}
else
{
if (order.OrderTax == 0 && _taxSettings.HideZeroTax)
{
displayTax = false;
displayTaxRates = false;
}
else
{
taxRates = new SortedDictionary<decimal, decimal>();
foreach (var tr in order.TaxRatesDictionary)
taxRates.Add(tr.Key, _currencyService.ConvertCurrency(tr.Value, order.CurrencyRate));
displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Any();
displayTax = !displayTaxRates;
var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate);
string taxStr = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, language);
cusTaxTotal = taxStr;
}
}
//discount
bool displayDiscount = false;
if (order.OrderDiscount > decimal.Zero)
{
var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate);
cusDiscount = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, language);
displayDiscount = true;
}
//total
var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate);
cusTotal = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, language);
//subtotal
sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.SubTotal", languageId), cusSubTotal));
//discount (applied to order subtotal)
if (displaySubTotalDiscount)
{
sb.AppendLine(string.Format("<tr style=\"text-align:right;\"><td> </td><td colspan=\"2\" style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{1}</strong></td> <td style=\"background-color: {0};padding:0.6em 0.4 em;\"><strong>{2}</strong></td></tr>", _templatesSettings.Color3, _localizationService.GetResource("Messages.Order.SubTotalDiscount", languageId), cusSubTotalDiscount));
}
示例14: MapDecoratedRoutes
/// <summary>
/// Looks for any action methods in 'assemblyToSearch' that have the RouteAttribute defined,
/// adding the routes to the parameter 'routes' collection.
/// </summary>
/// <param name="assemblyToSearch">An assembly containing Controllers with public methods decorated with the RouteAttribute</param>
public static void MapDecoratedRoutes(this RouteCollection routes, Assembly assemblyToSearch, Func<IDictionary<string, long>> getRouteWeights = null)
{
var decoratedMethods = from t in assemblyToSearch.GetTypes()
where t.IsSubclassOf(typeof(System.Web.Mvc.Controller))
from m in t.GetMethods()
where m.IsDefined(typeof(RouteAttribute), false)
select m;
var methodsToRegister = new SortedDictionary<RouteAttribute, MethodInfo>(); // sort urls alphabetically via RouteAttribute's IComparable implementation
var routeWeights = (getRouteWeights == null ? null : getRouteWeights()) ?? new Dictionary<string, long>();
// first, collect all the methods decorated with our RouteAttribute
foreach (var method in decoratedMethods)
{
var attrs = method.GetCustomAttributes(typeof(RouteAttribute), true).ToList();
foreach (var attr in attrs)
{
var ra = (RouteAttribute)attr;
if (!methodsToRegister.Any(p => p.Key.Url.Equals(ra.Url)))
{
long weight;
string key = (method.DeclaringType.Name + "/" + method.Name).Replace("Controller/", "/");
if (routeWeights.TryGetValue(key, out weight)) ra.SetWeight(weight);
methodsToRegister.Add(ra, method);
}
else
Debug.WriteLine("MapDecoratedRoutes - found duplicate url -> " + ra.Url);
}
}
Debug.WriteLine(string.Format("MapDecoratedRoutes - found {0} usable methods decorated with RouteAttribute", methodsToRegister.Count));
// now register the unique urls to the Controller.Method that they were decorated upon
foreach (var pair in methodsToRegister)
{
var attr = pair.Key;
var method = pair.Value;
var action = method.Name;
var controllerType = method.ReflectedType;
var controllerName = controllerType.Name.Replace("Controller", "");
var controllerNamespace = controllerType.FullName.Replace("." + controllerType.Name, "");
Debug.WriteLine(string.Format("MapDecoratedRoutes - mapping url '{0}' to {1}.{2}.{3}", attr.Url, controllerNamespace, controllerName, action));
var route = new LeftMatchingRoute(attr.Url, new MvcRouteHandler());
//var route = new Route(attr.Url, new MvcRouteHandler());
route.Defaults = new RouteValueDictionary(new { controller = controllerName, action = action });
// optional parameters are specified like: "users/filter/{filter?}"
if (attr.OptionalParameters != null)
{
foreach (var optional in attr.OptionalParameters)
route.Defaults.Add(optional, "");
}
// constraints are specified like: @"users/{id:\d+}" or "users/{id:INT}"
if (attr.Constraints != null)
{
route.Constraints = new RouteValueDictionary();
foreach (var constraint in attr.Constraints)
{
route.Constraints.Add(constraint.Key, constraint.Value);
}
}
// fully-qualify route to its controller method by adding the namespace; allows multiple assemblies to share controller names/routes
// e.g. StackOverflow.Controllers.HomeController, StackOverflow.Api.Controllers.HomeController
route.DataTokens = new RouteValueDictionary(new { namespaces = new[] { controllerNamespace } });
routes.Add(attr.Name, route);
}
}
示例15: PrintOrdersToPdf
//.........这里部分代码省略.........
else
{
//excluding tax
var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
string paymentMethodAdditionalFeeExclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);
var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeExclTaxStr), font));
p.HorizontalAlignment = Element.ALIGN_RIGHT;
p.Border = Rectangle.NO_BORDER;
totalsTable.AddCell(p);
}
}
//tax
string taxStr = string.Empty;
var taxRates = new SortedDictionary<decimal, decimal>();
bool displayTax = true;
bool displayTaxRates = true;
if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
{
displayTax = false;
}
else
{
if (order.OrderTax == 0 && _taxSettings.HideZeroTax)
{
displayTax = false;
displayTaxRates = false;
}
else
{
taxRates = order.TaxRatesDictionary;
displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Any();
displayTax = !displayTaxRates;
var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate);
taxStr = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang);
}
}
if (displayTax)
{
var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Tax", lang.Id), taxStr), font));
p.HorizontalAlignment = Element.ALIGN_RIGHT;
p.Border = Rectangle.NO_BORDER;
totalsTable.AddCell(p);
}
if (displayTaxRates)
{
foreach (var item in taxRates)
{
string taxRate = String.Format(_localizationService.GetResource("PDFInvoice.TaxRate", lang.Id), _priceFormatter.FormatTaxRate(item.Key));
string taxValue = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(item.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, lang);
var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", taxRate, taxValue), font));
p.HorizontalAlignment = Element.ALIGN_RIGHT;
p.Border = Rectangle.NO_BORDER;
totalsTable.AddCell(p);
}
}
//discount (applied to order total)
if (order.OrderDiscount > decimal.Zero)
{
var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate);
string orderDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang);