/// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="serialization"></param>
        private void BuildHeaderLine(StringBuilder builder, IDictionary<string, object> serialization)
        {
            var obj = serialization.FirstOrDefault();
            var lines = obj.Value as IList<object>;

            if (lines == null)
                lines = new List<object>(new[] { serialization });

            IDictionary line = lines.FirstOrDefault() as IDictionary;
            if (line != null)
            {
                IList<string> values = new List<string>();
                foreach (DictionaryEntry entry in line)
                {
                    if ((string)entry.Key == Serializer.ModelNameKey)
                        continue;

                    if (!(entry.Key is string))
                        throw new ArgumentException("Key of serialization dictionary must be a string.", "serialization");

                    var key = (entry.Key ?? "").ToString().Replace(FieldDefinition, FieldDefinitionEscape);
                    values.Add(FieldDefinition + key + FieldDefinition);
                }
                builder.Append(String.Join(SeperatorCharacter.ToString(), values.ToArray()));
                builder.Append(LineTermination);
            }
        }
 public KeyValuePair<string, string> GetKey(string typeName, IDictionary<string, object> values)
 {
     var fields = GetFields(typeName);
     var keyField = fields.First(o => o.IsKey);
     var kvp = values.FirstOrDefault(o => o.Key == keyField.FieldName);
     return new KeyValuePair<string, string>(kvp.Key, (kvp.Value ?? "").ToString());
 }
            public TemplateResult(bool success, IDictionary<string,string> dic)
            {
                var key = dic.FirstOrDefault();

                Name = key.Key;
                Value = key.Value;
                Success = success;
            }
        /// <summary>
        /// Internal constructor - the initialization of this exception may only be done internally from the ModelWithValidation class
        /// </summary>
        /// <param name="validationErrors"></param>
        internal ValidationException(IDictionary<string, IList<string>> validationErrors)
            : base((validationErrors == null || validationErrors.Count == 0)
                       ? ""
                       : (
                             validationErrors.Count == 1 && validationErrors.FirstOrDefault().Value.Count == 1
                                 ? String.Format("Validation of property \"{0}\" failed with reason: \"{1}\".",
                                                 validationErrors.FirstOrDefault().Key, validationErrors.FirstOrDefault().Value[0])
                                 : "Multiple validation errors occurred"))
        {
            if (validationErrors == null || validationErrors.Count == 0 || validationErrors.FirstOrDefault().Value.Count == 0)
            {
                throw new ArgumentNullException("validationErrors", "Should be not null or empty");
            }

            foreach (var _validationError in validationErrors)
            {
                Data.Add(_validationError.Key, _validationError.Value);
            }
        }
        public object Handle(IDictionary<string, object> sourceList, MapperConfig config)
        {
            string sourceName = config.SourceName.FirstOrDefault();
            if (sourceName == null)
                throw new ArgumentException("Incorrect field name for mapped to {0}", config.DestinationName);

            string[] values = sourceList.FirstOrDefault(x => x.Key.Equals(sourceName)).Value as string[];

            return string.Join(",", values);
        }
        /// <summary>
        /// Given an IDictionary of mappings between old and new URLs, converts the URL
        /// in every Preview in the JdfTree to the appropriate new URL.
        /// </summary>
        /// <param name="ticket">The Ticket to process</param>
        /// <param name="urlMapping">A IDictionary keyed by existing URLs mapping to new System.Uri</param>
        /// <param name="mustMapCIDs">If <i>true</i> throws an exception if an existing URL starts with CID and
        /// no mapping has been provided for that CID.</param>
        /// <exception cref="JdfException">Thrown if mustMapCIDs is true and no mapping was supplied for a CID-based URL.</exception>
        public static void MapPreviewUrls(Ticket ticket, IDictionary<string, string> urlMapping, bool mustMapCIDs) {

            var previews = ticket.Root.SelectJDFDescendants(Element.Preview);

            foreach (var preview in previews) {
                var urlValue = preview.GetAttributeValueOrNull("URL");
                if (urlValue != null) {
                    string newUrl = urlMapping.FirstOrDefault(item => item.Key.Equals(urlValue, StringComparison.OrdinalIgnoreCase)).Value;
                    if (newUrl != null) {
                        preview.AddOrReplaceAttribute(new XAttribute("URL", (new Uri(newUrl)).AbsoluteUri));
                    }
                    else {
                        if (urlValue.StartsWith("cid:", StringComparison.OrdinalIgnoreCase) && mustMapCIDs) {
                            throw new JdfException(string.Format(FluentJdf.Resources.Messages.MustMapCIDsIsTrueAndNoMappingSuppliedForURL, urlValue));
                        }
                    }
                }
            }
        }
Example #7
0
        private bool GetRootParent(int categoryId, IDictionary<string, object> source)
        {
            var item = source.FirstOrDefault(t => t.Key.Equals(categoryId.ToString()));
            {
                var valueCate = item.Value as Dictionary<string, object>;
                var parents = (valueCate["parents"] as object[]);
                if (parents.Count() > 0)
                {
                    int pId = int.Parse(parents[0].ToString());
                    if (pId == rootId)
                        return true;
                    else
                        return GetRootParent(pId, source);
                }

            }

            return false;
        }
Example #8
0
        static Task RunWorkers(IDictionary<Task, StateExpander> workers)
        {
            var setMinScores = new Action<int, StateExpander[]>((newMin, workObjects) =>
            {
                _globalMin = Math.Min(_globalMin, newMin);
                foreach (var stateExpander in workObjects)
                {
                    stateExpander.SetMinScore(newMin);
                }
            });

            var continueAction = new Action<Task>(task =>
            {
                lock(workers)
                {
                    var resultData = workers[task];

                    Console.WriteLine("\n\nThread complete: {0}", task.Id);
                    Console.WriteLine("Min score: {0}", resultData.MinScore);

                    var nextWorker = workers.FirstOrDefault(m => m.Key.Id == _nextThreadId);
                    if (nextWorker.Key != null)
                    {
                        Console.WriteLine("Starting thread: {0}", nextWorker.Key.Id);
                        nextWorker.Key.Start();
                        _nextThreadId += 1;
                    }
                }
            });

            var result = new Task(() =>
            {
                var workTasks = workers.Select(m => m.Key).ToArray();
                var workObjects = workers.Select(m => m.Value).ToArray();

                foreach (var stateExpander in workObjects)
                {
                    stateExpander.NewMinFound += newMin => setMinScores(newMin, workObjects);
                }

                lock (workers)
                {
                    foreach (var stateExpander in workTasks)
                    {
                        stateExpander.ContinueWith(continueAction);

                        if (_nextThreadId <= MaxConcurrentWorkers)
                        {
                            Console.WriteLine("Starting thread: {0}", stateExpander.Id);
                            stateExpander.Start();
                            _nextThreadId += 1;
                        }
                    }
                }

                Task.WaitAll(workTasks);
            });

            result.Start();
            return result;
        }
        internal void MapMessageUrls(Message message, IDictionary<string, string> urlMapping) {
            // Access the URL in the QueueSubmissionParams or ResubmissionParams of each Command element in the JMF.
            foreach (var command in message.Root.SelectJDFDescendants(Element.Command)) {
                bool toProcess = false;

                var commandType = command.GetAttributeValueOrNull("Type");

                IEnumerable<XElement> submissionParams = null;

                if (commandType == Command.SubmitQueueEntry) {
                    submissionParams = command.SelectJDFDescendants(Element.QueueSubmissionParams);
                    if (submissionParams.Count() == 0) {
                        throw new JdfException(FluentJdf.Resources.Messages.QueueSubmissionParamsAreRequiredInSubmitQueueEntry);
                    }
                    else {
                        toProcess = true;
                    }
                }
                if (commandType == Command.ResubmitQueueEntry) {
                    submissionParams = command.SelectJDFDescendants(Element.ResubmissionParams);
                    if (submissionParams.Count() == 0) {
                        throw new JdfException(FluentJdf.Resources.Messages.ReSubmissionParamsAreRequiredInResubmitQueueEntry);
                    }
                    else {
                        toProcess = true;
                    }
                }
                if (toProcess) {
                    string jdfUrl = submissionParams.First().GetAttributeValueOrNull("URL").ToString().ToLower();
                    string newUrl = urlMapping.FirstOrDefault(item => item.Key.Equals(jdfUrl, StringComparison.OrdinalIgnoreCase)).Value;
                    if (newUrl != null) {
                        submissionParams.First().AddOrReplaceAttribute(new XAttribute("URL", (new Uri(newUrl)).AbsoluteUri));
                    }
                }
            }
        }
        private static void SetParameters(Procedure procedure, IDbCommand cmd, IDictionary<string, object> suppliedParameters)
        {
            var returnParameter = procedure.Parameters.FirstOrDefault(p => p.Direction == ParameterDirection.ReturnValue);
            if (returnParameter!=null)
            {
                var cmdParameter = cmd.CreateParameter();
                cmdParameter.ParameterName = SimpleReturnParameterName;
                cmdParameter.Size = returnParameter.Size;
                cmdParameter.Direction = ParameterDirection.ReturnValue;
                cmdParameter.DbType = returnParameter.Dbtype;
                cmd.Parameters.Add(cmdParameter);
            }

            int i = 0;
            
            foreach (var parameter in procedure.Parameters.Where(p => p.Direction != ParameterDirection.ReturnValue))
            {
                //Tim Cartwright: Allows for case insensive parameters
                var value = suppliedParameters.FirstOrDefault(sp => 
                    sp.Key.Equals(parameter.Name.Replace("@", ""), StringComparison.InvariantCultureIgnoreCase)
                    || sp.Key.Equals("_" + i)
                );
                var cmdParameter = cmd.CreateParameter();
                //Tim Cartwright: method AddParameter does not allow for the "default" keyword to ever be passed into 
                //  parameters in stored procedures with defualt values. Null is always sent in. This will allow for default 
                //  values to work properly. Not sure why this is so, in both cases the value gets set. Just is.
                //var cmdParameter = cmd.AddParameter(parameter.Name, value);
                cmdParameter.ParameterName = parameter.Name;
                cmdParameter.Value = value.Value; 
                cmdParameter.Direction = parameter.Direction;
                //Tim Cartwright: I added size and dbtype so inout/out params would function properly.
                //not setting the proper dbtype and size with out put parameters causes the exception: "Size property has an invalid size of 0"
                // Mark: Just adding a quick check here so that if the Provider-specific type has been set by setting the value, this will not
                // override that.
                if (cmdParameter.DbType != parameter.Dbtype)
                {
                    cmdParameter.DbType = parameter.Dbtype;
                }
                cmdParameter.Size = parameter.Size;
                cmd.Parameters.Add(cmdParameter);
                i++;
            }
        }
Example #11
0
        /// <summary>
        /// </summary>
        /// <param name="namedTypeSymbol">
        /// </param>
        /// <param name="map">
        /// </param>
        /// <param name="resolvedTypes">
        /// </param>
        /// <returns>
        /// </returns>
        private static bool SelectGenericsFromArgumentsForOneLevel(
            NamedTypeSymbol namedTypeSymbol, IDictionary<IType, IType> map, List<TypeSymbol> resolvedTypes)
        {
            foreach (var typeSymbol in namedTypeSymbol.TypeArguments)
            {
                if (typeSymbol.Kind == SymbolKind.TypeParameter)
                {
                    var foundType = map.FirstOrDefault(pair => pair.Key.Name == typeSymbol.Name);
                    if (foundType.Key == null)
                    {
                        return false;
                    }

                    resolvedTypes.Add((foundType.Value as MetadataTypeAdapter).TypeDef);
                    continue;
                }

                var subTypeNamedTypeSymbol = typeSymbol as NamedTypeSymbol;
                if (subTypeNamedTypeSymbol != null && subTypeNamedTypeSymbol.Arity > 0)
                {
                    resolvedTypes.Add(ConstructGenericTypeSymbol(subTypeNamedTypeSymbol, map));
                    continue;
                }

                resolvedTypes.Add(subTypeNamedTypeSymbol);
            }

            return true;
        }
Example #12
0
        private static void ClearTypesIn(IDictionary<string, string> dictionary, string typeName = null)
        {
            if (String.IsNullOrWhiteSpace(typeName))
            {
                dictionary.Clear();
            }
            else
            {
                KeyValuePair<string, string>? pair = dictionary.FirstOrDefault(x => x.Value.Equals(typeName));

                if (pair != null && pair.Value.Key != null)
                    dictionary.Remove(pair.Value.Key);
            }
        }
 private static ApiObject FindObject(IHasName apiObject, IDictionary<string, ApiObject> objects, string key)
 {
     var foundKey = objects.Keys.FirstOrDefault(k => string.Equals(k, key));
     var obj = foundKey != null ? objects[foundKey] : objects.FirstOrDefault(o => o.Value.Name == apiObject.Name).Value;
     return obj;
 }
 private Action FirstOrDefaultQuickFix(IDictionary<string, Action> fixes)
 {
     return fixes.FirstOrDefault().Value;
 }
Example #15
0
        /// <summary>
        /// Serializes to json.
        /// </summary>
        /// <param name="serialization">The serialization.</param>
        /// <returns></returns>
        private void BuildLine(StringBuilder builder, IDictionary<string, object> serialization)
        {
            var obj = serialization.FirstOrDefault();
            var lines = obj.Value as IList<object>;

            if (lines == null)
                lines = new List<object>(new[] { serialization });

            foreach (var line in lines.Cast<IDictionary>())
            {
                if (line != null)
                {
                    IList<string> values = new List<string>();
                    foreach (DictionaryEntry entry in line)
                    {
                        if (!(entry.Key is string))
                            throw new ArgumentException("Key of serialization dictionary must be a string.", "serialization");

                        values.Add((entry.Value ?? "").ToString());
                    }
                    builder.Append(String.Join(SeperatorCharacter.ToString(), values.ToArray()));
                    builder.Append(LineTermination);
                }
            }
        }
Example #16
0
 private string GetValueFromParameters(string key, IDictionary<string, object> paras, object defaultValue)
 {
     if (key.StartsWith("{") && key.EndsWith("}"))
     {
         string paraName = key.Substring(1, key.Length - 2).ToLower();
         var para = paras.FirstOrDefault(o => o.Key.ToLower() == paraName);
         object paraVal = default(KeyValuePair<string,object>).Equals(para) ? defaultValue : para.Value;
         return paraVal == null ? defaultValue.ToString() : paraVal.ToString();
     }
     return defaultValue.ToString();
 }
    public override string ProcessOrder([NotNull] Order order, IDictionary<string, object> parameters)
    {
      Assert.ArgumentNotNull(order, "order");
      Assert.ArgumentNotNull(parameters, "parameters");

      Assert.IsNotNull(parameters.FirstOrDefault(p => p.Key == "orderlineid").Value, "Order line ID should be passed as parameter.");
      Assert.IsNotNull(parameters.FirstOrDefault(p => p.Key == "productcode").Value, "Product code should be passed as parameter.");
      Assert.IsNotNull(parameters.FirstOrDefault(p => p.Key == "quantity").Value, "Quantity should be passed as parameter.");

      string productCode = parameters["productcode"].ToString();
      Assert.IsTrue(productCode != string.Empty, "Product code must not be empty");

      long quantity = long.Parse(parameters["quantity"].ToString());
      long orderLineId = long.Parse(parameters["orderlineid"].ToString());

      // Resolving of the OrderLine.
      OrderLine orderLine = order.OrderLines.Single(ol => ol.Alias == orderLineId);
      Assert.IsNotNull(orderLine, "Cannot resolve order line");

      this.SetOrderStates(order);

      // Resolving of the Stock.
      ProductStockInfo currentProductStockInfo = new ProductStockInfo
      {
        ProductCode = orderLine.LineItem.Item.Code
      };
      long currentProductStock = this.productStockManager.GetStock(currentProductStockInfo).Stock;

      ProductStockInfo newProductStockInfo = new ProductStockInfo
      {
        ProductCode = productCode
      };
      long newProductStock = this.productStockManager.GetStock(newProductStockInfo).Stock;

      if (newProductStock < quantity)
      {
        return CustomResults.OutOfStock.ToString();
      }

      // Updating of the stock
      this.productStockManager.Update(currentProductStockInfo, currentProductStock + (long)orderLine.LineItem.Quantity);
      this.productStockManager.Update(newProductStockInfo, newProductStock - quantity);

      this.FormattedMessageForOldOrderLine = this.CreateFormattedMessage(orderLine);

      // Updating of the LineItem
      Assert.IsNotNull(this.orderLineFactory, "OrderLineFactory cannot be null.");
      LineItem newLineItem = this.orderLineFactory.CreateLineItemFromOrder(order, productCode, quantity);
      orderLine.LineItem.CopyLineItemFrom(newLineItem);

      this.FormattedMessageForNewOrderLine = this.CreateFormattedMessage(orderLine);

      // Recalculate taxable amount.
      order = this.UpdateTaxesForOrder(order, orderLine);

      // Saving of the Order)
      this.merchantOrderManager.Save(order);

      return SuccessfulResult;
    }