Пример #1
0
        //for simplicity keep it bool, but an enum with different status codes would be more useful
        //also would probably want to return the order
        /// <summary>
        ///     Creates the specified customer.
        /// </summary>
        /// <param name="customer">The customer.</param>
        /// <param name="evt">The evt.</param>
        /// <param name="amount">The amount.</param>
        /// <param name="quantity">The quantity.</param>
        /// <param name="creditCard">The credit card.</param>
        /// <returns></returns>
        public OrderResult Create(Customer customer, Event evt, int amount, int quantity, CreditCard creditCard)
        {
            var result = new OrderResult();
            try
            {
                //as above, don't believe permission logic  belongs here

                var user = (User) Thread.CurrentPrincipal.Identity;
                var order = new Order(Guid.NewGuid(), customer, creditCard, amount, quantity, evt, DateTime.Now, user);

                //validation on order failed
                if (order.HasErrors())
                {
                    result.Status = Status.Fail;
                    result.Data = order.Errors;
                    return result;
                }

                //order successful
                result.Id = order.Id;
                result.Status = Status.Ok;
                return result;
            }
                //not sure if this should really occur at a lover level
            catch (Exception ex)
            {
                File.AppendAllText(@"C:\Errors.txt", ex.Message);
                result.Status = Status.Fail;
                return result;
            }
        }
Пример #2
0
        public ActionResult Get(Guid id) {
            var order = Db.Orders.SingleOrDefault(x => x.Id == id);

            if (order == null) {
                return HttpNotFound();
            }

            var result = new OrderResult() {
                Number = order.Number,
                CreatedDate = order.CreatedDate,
                DeliveryAddress = order.DeliveryAddress,
                HeadOfficeAddress = new AddressResult() {
                    City = "New York"
                }.WithUpdate(() => Patch(id, null))
            }
                .WithParent(() => All())
                .WithAction(() => Create(), "Create New");

            result.ConfigureProperty(x => x.Number, x => x.WithAction(() => Patch(id, ""), "")
        );

            return result.CreateActionResult();
        }
Пример #3
0
 protected override void When()
 {
     _result = SUT.Process(new Order {
         PartNumber = "TestPart", Quantity = -1
     });
 }
Пример #4
0
        async Task <Product> TrackProduct(Product product, CancellationTokenSource token)
        {
            logger.LogInformation($"[{DateTime.Now:dd.MM.yyy HH.mm.ss}] Отслеживаю товар ID: {product.ArtNumber} с максимальной ценой: {product.MaxPrice.ToString("C", OrderBot.culture)}");
            product.TrackedStatus = TrackedStatus.Active;
            DateTime maxPriceCheckTimestamp = DateTime.Now;
            bool     isFirstAttempt         = true;

            while (!token.IsCancellationRequested)
            {
                IDocument document = await context.OpenAsync($"{PRODUCT_LINK}{product.ArtNumber}htm");

                bool productNotFound = document.All.Where(x => x.HasAttribute("class") && x.GetAttribute("class").Equals("top")).Select(x => x.TextContent).Any(x => x.Contains("Товар не найден"));
                if (productNotFound)
                {
                    product.TrackedStatus = TrackedStatus.ProductNotFound;
                    break;
                }
                string cookie        = document.Cookie.Split("PHPSESSID=")[1];
                string productName   = document.All.Where(x => x.HasAttribute("id") && x.GetAttribute("id").Equals(PRODUCT_NAME)).Select(x => x.TextContent).FirstOrDefault();
                string productStatus = document.All.Where(x => x.HasAttribute("class") && x.GetAttribute("class").Contains(PRODUCT_STATUS)).Select(x => x.TextContent).FirstOrDefault();
                product.ProductName = productName;
                if (productStatus == PRODUCT_IN_STOCK)
                {
                    var    productToken = document.All.Where(x => x.HasAttribute("name") && x.GetAttribute("name").Equals("token")).Select(x => x.Attributes.GetNamedItem("value").Value).FirstOrDefault();
                    string price        = document.All.Where(x => x.HasAttribute("itemprop") && x.GetAttribute("itemprop").Equals("price")).Select(x => x.Attributes.GetNamedItem("content").Value).FirstOrDefault();
                    if (IsMaxPriceCheck(price, product.MaxPrice, out double currentPrice))
                    {
                        product.CurrentPrice = currentPrice;
                        OrderResult orderResult = await orderBot.OrderProduct(product, productToken, cookie);

                        if (orderResult.TrackedStatus == TrackedStatus.ProductOrdered)
                        {
                            IHtmlDocument orderDocument = parser.ParseDocument(orderResult.Content);
                            string        orderNumber   = orderDocument.All.Where(x => x.HasAttribute("class") && x.GetAttribute("class").Equals("green")).Select(x => x.TextContent).FirstOrDefault();
                            if (!string.IsNullOrEmpty(orderNumber))
                            {
                                product.TrackedStatus = orderResult.TrackedStatus;
                                orderBot.ProductSuccessfulOrdered(product, orderNumber);
                            }
                        }
                        else if (orderResult.TrackedStatus == TrackedStatus.FailOrderProcess)
                        {
                            logger.LogCritical($"[{DateTime.Now:dd.MM.yyy HH.mm.ss}] В процессе заказа товара [{product.ArtNumber}] {productName} возникла ошибка (код https запроса не в диапазоне 200-299)");
                        }
                    }
                    else
                    {
                        product.CurrentPrice = currentPrice;
                        await orderBot.ProductPriceLargerMaxPrice(product, maxPriceCheckTimestamp, isFirstAttempt).ContinueWith((task) =>
                        {
                            if (task.Result)
                            {
                                isFirstAttempt         = false;
                                maxPriceCheckTimestamp = DateTime.Now;
                            }
                        });
                    }
                }
                if (!token.IsCancellationRequested)
                {
                    Task.Delay(5000).Wait();
                }
            }
            return(await Task.FromResult(product));
        }
Пример #5
0
 public void When_processing_an_order()
 {
     _result = SUT.Process(new Order {
         PartNumber = "TestPart", Quantity = 10
     });
 }
Пример #6
0
            private static ISearchResponse <Lib.Data.Smlouva> _coreSearch(QueryContainer query, int page, int pageSize,
                                                                          OrderResult order,
                                                                          AggregationContainerDescriptor <Lib.Data.Smlouva> anyAggregation = null,
                                                                          bool?platnyZaznam     = null, bool includeNeplatne    = false, bool logError = true,
                                                                          bool withHighlighting = false, bool exactNumOfResults = false)
            {
                page = page - 1;
                if (page < 0)
                {
                    page = 0;
                }

                if (page * pageSize >= MaxResultWindow) //elastic limit
                {
                    page = 0; pageSize = 0;             //return nothing
                }

                AggregationContainerDescriptor <Lib.Data.Smlouva> baseAggrDesc = null;

                baseAggrDesc = anyAggregation == null ?
                               null //new AggregationContainerDescriptor<HlidacStatu.Lib.Data.Smlouva>().Sum("sumKc", m => m.Field(f => f.CalculatedPriceWithVATinCZK))
                        : anyAggregation;

                Func <AggregationContainerDescriptor <Lib.Data.Smlouva>, AggregationContainerDescriptor <Lib.Data.Smlouva> > aggrFunc
                    = (aggr) => { return(baseAggrDesc); };

                ISearchResponse <Lib.Data.Smlouva> res = null;

                try
                {
                    var client = Lib.ES.Manager.GetESClient();
                    if (platnyZaznam.HasValue && platnyZaznam == false)
                    {
                        client = Lib.ES.Manager.GetESClient_Sneplatne();
                    }
                    Indices indexes = client.ConnectionSettings.DefaultIndex;
                    if (includeNeplatne)
                    {
                        indexes = ES.Manager.defaultIndexName_SAll;
                    }

                    res = client
                          .Search <Lib.Data.Smlouva>(s => s
                                                     .Index(indexes)
                                                     .Size(pageSize)
                                                     .From(page * pageSize)
                                                     .Query(q => query)
                                                     .Source(m => m.Excludes(e => e.Field(o => o.Prilohy)))
                                                     .Sort(ss => GetSort(order))
                                                     .Aggregations(aggrFunc)
                                                     .Highlight(h => Lib.Searching.Tools.GetHighlight <Data.Smlouva>(withHighlighting))
                                                     .TrackTotalHits(exactNumOfResults || page * pageSize == 0 ? true : (bool?)null)
                                                     );
                    if (withHighlighting && res.Shards != null && res.Shards.Failed > 0) //if some error, do it again without highlighting
                    {
                        res = client
                              .Search <Lib.Data.Smlouva>(s => s
                                                         .Index(indexes)
                                                         .Size(pageSize)
                                                         .From(page * pageSize)
                                                         .Query(q => query)
                                                         .Source(m => m.Excludes(e => e.Field(o => o.Prilohy)))
                                                         .Sort(ss => GetSort(order))
                                                         .Aggregations(aggrFunc)
                                                         .Highlight(h => Lib.Searching.Tools.GetHighlight <Data.Smlouva>(false))
                                                         .TrackTotalHits(exactNumOfResults || page * pageSize == 0 ? true : (bool?)null)
                                                         );
                    }
                }
                catch (Exception e)
                {
                    if (res != null && res.ServerError != null)
                    {
                        Lib.ES.Manager.LogQueryError <Lib.Data.Smlouva>(res, query.ToString());
                    }
                    else
                    {
                        HlidacStatu.Util.Consts.Logger.Error("", e);
                    }
                    throw;
                }

                if (res.IsValid == false && logError)
                {
                    Lib.ES.Manager.LogQueryError <Lib.Data.Smlouva>(res, query.ToString());
                }

                return(res);
            }
Пример #7
0
        private OrderResult ParsOrderSult(string rtnValues)
        {
            try
            {
                OrderResult or = new OrderResult();
                HtmlAgilityPack.HtmlDocument docResult = new HtmlAgilityPack.HtmlDocument();
                docResult.LoadHtml(rtnValues);
                var divs = docResult.DocumentNode.Descendants("div");
                foreach (var div in divs)
                {
                    if (div.InnerHtml.IndexOf("<span style=\"color:blue\">查詢序號:") > 0)
                    {
                        int p1 = div.InnerHtml.IndexOf("查詢序號:</span>");
                        int p11 = div.InnerHtml.IndexOf("<BR>", p1 + 12, StringComparison.OrdinalIgnoreCase); //找到查詢序號後的那個"<br>"字樣

                        //取出查詢序號
                        or.QueryNumber = div.InnerHtml.Substring(p1 + 12, p11 - (p1 + 12));
                        //取出查詢密碼
                        int p2 = div.InnerHtml.IndexOf("查詢密碼:</span>");
                        int p22 = div.InnerHtml.IndexOf("<BR>", p2 + 12, StringComparison.OrdinalIgnoreCase); //找到查詢密碼後的那個"<br>"字樣
                        or.QueryPwd = div.InnerHtml.Substring(p2 + 12, p22 - (p2 + 12));
                        break;
                    }
                }
                return or;
            }
            catch (ApplicationException ex)
            {
                throw new Exception("error at ParsOrderSult()" + ex.Message);
            }
        }
Пример #8
0
 /// <nodoc />
 public static int ToCompareResult(this OrderResult orderResult) => (int)orderResult;
Пример #9
0
 public static Nest.ISearchResponse <Lib.Data.Smlouva> RawSearch(string jsonQuery, int page, int pageSize, OrderResult order      = OrderResult.Relevance,
                                                                 AggregationContainerDescriptor <Lib.Data.Smlouva> anyAggregation = null, bool?platnyZaznam = null,
                                                                 bool includeNeplatne = false, bool exactNumOfResults = false
                                                                 )
 {
     return(RawSearch(Searching.Tools.GetRawQuery(jsonQuery), page, pageSize, order, anyAggregation, platnyZaznam, includeNeplatne,
                      exactNumOfResults: exactNumOfResults));
 }
Пример #10
0
            public static SmlouvaSearchResult SimpleSearch(string query, int page, int pageSize, OrderResult order,
                                                           AggregationContainerDescriptor <Lib.Data.Smlouva> anyAggregation = null,
                                                           bool?platnyZaznam     = null, bool includeNeplatne    = false, bool logError = true, bool fixQuery = true,
                                                           bool withHighlighting = false, bool exactNumOfResults = false)
            {
                var result = new SmlouvaSearchResult()
                {
                    Page      = page,
                    PageSize  = pageSize,
                    OrigQuery = query,
                    Q         = query,
                    Order     = ((int)order).ToString()
                };

                if (string.IsNullOrEmpty(query))
                {
                    result.Result  = null;
                    result.IsValid = false;
                    result.Total   = 0;
                    return(result);
                }

                Devmasters.Core.StopWatchEx sw = new Devmasters.Core.StopWatchEx();
                sw.Start();

                if (fixQuery)
                {
                    query    = Searching.Tools.FixInvalidQuery(query, irules, Searching.Tools.DefaultQueryOperators);
                    result.Q = query;
                }
                if (logError && result.Q != result.OrigQuery)
                {
                    HlidacStatu.Util.Consts.Logger.Debug(new Devmasters.Core.Logging.LogMessage()
                                                         .SetMessage("Fixed query")
                                                         .SetCustomKeyValue("runningQuery", result.Q)
                                                         .SetCustomKeyValue("origQuery", result.OrigQuery)
                                                         );
                }

                if (platnyZaznam.HasValue)
                {
                    query = Lib.Searching.Tools.ModifyQueryAND(query, "platnyZaznam:" + platnyZaznam.Value.ToString().ToLower());
                }


                ISearchResponse <Lib.Data.Smlouva> res =
                    _coreSearch(GetSimpleQuery(query), page, pageSize, order, anyAggregation, platnyZaznam,
                                includeNeplatne, logError, withHighlighting, exactNumOfResults);

                Data.Audit.Add(Data.Audit.Operations.Search, "", "", "Smlouva", res.IsValid ? "valid" : "invalid", query, null);

                if (res.IsValid == false && logError)
                {
                    Lib.ES.Manager.LogQueryError <Lib.Data.Smlouva>(res, query);
                }

                sw.Stop();

                result.ElapsedTime = sw.Elapsed;
                try
                {
                    result.Total = res?.Total ?? 0;
                }
                catch (Exception)
                {
                    result.Total = 0;
                }
                result.IsValid        = res?.IsValid ?? false;
                result.ElasticResults = res;
                return(result);
            }
Пример #11
0
            public static SmlouvaSearchResult SearchRaw(QueryContainer query, int page, int pageSize, OrderResult order,
                                                        AggregationContainerDescriptor <Lib.Data.Smlouva> anyAggregation = null,
                                                        bool?platnyZaznam     = null, bool includeNeplatne = false, bool logError = true, bool fixQuery = true,
                                                        bool withHighlighting = false)
            {
                var result = new SmlouvaSearchResult()
                {
                    Page      = page,
                    PageSize  = pageSize,
                    OrigQuery = "",
                    Q         = "",
                    Order     = ((int)order).ToString()
                };

                ISearchResponse <Lib.Data.Smlouva> res = _coreSearch(query, page, pageSize, order, anyAggregation, platnyZaznam,
                                                                     includeNeplatne, logError, withHighlighting);


                if (res.IsValid == false && logError)
                {
                    Lib.ES.Manager.LogQueryError <Lib.Data.Smlouva>(res, query.ToString());
                }


                result.Total          = res?.Total ?? 0;
                result.IsValid        = res?.IsValid ?? false;
                result.ElasticResults = res;
                return(result);
            }
Пример #12
0
 // To be called when the executor of this order was rendered incapable of complying with this order.
 protected void Fail(Unit executor, OrderResult reason)
 {
     executor.ClearCurrentOrder();
 }
Пример #13
0
 private static bool CompareOrderResult(OrderResult expected, OrderResult actual) =>
 expected.Status == actual.Status &&
 (expected.Downloads == null && actual.Downloads == null) ||
 (expected.Downloads.Length == actual.Downloads.Length &&
  expected.Downloads.Zip(actual.Downloads, (a, b) => (a, b)).All(x => x.Item1 == x.Item2));
Пример #14
0
        public async Task <IHttpActionResult> GetOrdersByPost(int postId, int state, string key, int pageSize, int page, string order, bool isAsc)
        {
            PageResult <OrderResult> result = new PageResult <OrderResult>();
            List <OrderResult>       data   = new List <OrderResult>();
            OrderResult ord    = new OrderResult();
            var         orders = db.Orders.Include(o => o.Compensations).Where(o => o.PostUserId == postId)
                                 .Where(o => state < 0 ? true : (int)o.State == state)
                                 .Where(o => o.State != OrderState.已删除)
                                 .Where(o => (key == "" || key == null) ? true : (o.OrderNO.IndexOf(key) > -1 ||
                                                                                  o.TradeNO.IndexOf(key) > -1 || o.Student.Name.IndexOf(key) > -1)
                                        );

            var count = orders.Select(o => o.Id).Count();

            if (count == 0)
            {
                result.Count  = 0;
                ord.orders    = null;
                ord.statistic = null;
                data.Add(ord);
                result.Data        = data;
                result.CurrentPage = 1;
                result.Order       = order;
                result.IsAsc       = isAsc;
                result.PageSize    = pageSize;
                return(Ok(result));
            }
            var os = isAsc ? LinqOrder.DataSort(orders, order, "asc") : LinqOrder.DataSort(orders, order, "desc");

            result.Count = count;
            ord.orders   = await os.Skip((page - 1) *pageSize).Take(pageSize).Select(o => new OrderAllInfoWithProductIds()
            {
                Id              = o.Id,
                StudentID       = o.StudentID,
                TradeNO         = o.TradeNO,
                OrderNO         = o.OrderNO,
                PostUserId      = o.PostUserId,
                OrderDate       = o.OrderDate,
                ReceiptID       = o.ReceiptID,
                ActualPay       = o.OrderDetails.Sum(d => d.ActualPay),
                State           = o.State,
                PayDate         = o.PayDate,
                Channel         = o.Channel,
                IsDebt          = o.IsDebt,
                IsOtherDiscount = o.IsOtherDiscount,
                Debt            = o.OrderDetails.Sum(d => d.Debt),
                Remark          = o.Remark,
                Student         = o.Student,
                ProductIds      = o.OrderDetails.Select(od => od.ProductId).ToList(),
                Compensations   = o.Compensations.ToList(),
                HasCompensation = o.Compensations.Count() > 0
            }).ToListAsync();

            if (state == 1)
            {
                ord.statistic = await db.OrderDetails.Where(o => o.Order.PostUserId == postId)
                                .Where(o => (int)o.Order.State == state)
                                .GroupBy(o => o.Product.ProductName)
                                .Select(g => new StatiticDataItem()
                {
                    ProductName = g.Key,
                    Count       = g.Count(),
                    Debt        = g.Sum(o => o.Debt),
                    Discount    = g.Sum(o => o.Discount),
                    Pay         = g.Sum(o => o.ActualPay)
                }).ToListAsync();
            }
            else
            {
                ord.statistic = null;
            }
            data.Add(ord);
            result.Data        = data;
            result.CurrentPage = page;
            result.Order       = order;
            result.IsAsc       = isAsc;
            result.PageSize    = pageSize;
            return(Ok(result));
        }
Пример #15
0
 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
 {
     this.currentOrder = Warehouse.Logic.Warehouse.GetOrder(this.listBox1.SelectedItem.ToString());
     this.listBox2.SetSelected(this.listBox1.SelectedIndex, true);
 }
Пример #16
0
 public OrderResult KillOrder(OrderResult orderResult)
 {
     return(KillOrder(orderResult.TransId, orderResult.OrderNumber));
 }
Пример #17
0
            public static Nest.ISearchResponse <Lib.Data.Smlouva> RawSearch(Nest.QueryContainer query, int page, int pageSize, OrderResult order = OrderResult.Relevance,
                                                                            AggregationContainerDescriptor <Lib.Data.Smlouva> anyAggregation     = null, bool?platnyZaznam = null,
                                                                            bool includeNeplatne  = false,
                                                                            bool withHighlighting = false, bool exactNumOfResults = false
                                                                            )
            {
                var res = _coreSearch(query, page, pageSize, order, anyAggregation, platnyZaznam: platnyZaznam, includeNeplatne: includeNeplatne, logError: true, withHighlighting: withHighlighting, exactNumOfResults: exactNumOfResults);

                return(res);
            }
Пример #18
0
            public static SortDescriptor <Data.Smlouva> GetSort(OrderResult order)
            {
                SortDescriptor <Data.Smlouva> s = new SortDescriptor <Data.Smlouva>().Field(f => f.Field("_score").Descending());

                switch (order)
                {
                case OrderResult.DateAddedDesc:
                    s = new SortDescriptor <Data.Smlouva>().Field(m => m.Field(f => f.casZverejneni).Descending());
                    break;

                case OrderResult.DateAddedAsc:
                    s = new SortDescriptor <Data.Smlouva>().Field(m => m.Field(f => f.casZverejneni).Ascending());
                    break;

                case OrderResult.DateSignedDesc:
                    s = new SortDescriptor <Data.Smlouva>().Field(m => m.Field(f => f.datumUzavreni).Descending());
                    break;

                case OrderResult.DateSignedAsc:
                    s = new SortDescriptor <Data.Smlouva>().Field(m => m.Field(f => f.datumUzavreni).Ascending());
                    break;

                case OrderResult.PriceAsc:
                    s = new SortDescriptor <Data.Smlouva>().Field(m => m.Field(f => f.CalculatedPriceWithVATinCZK).Ascending());
                    break;

                case OrderResult.PriceDesc:
                    s = new SortDescriptor <Data.Smlouva>().Field(m => m.Field(f => f.CalculatedPriceWithVATinCZK).Descending());
                    break;

                case OrderResult.FastestForScroll:
                    s = new SortDescriptor <Data.Smlouva>().Field(f => f.Field("_doc"));
                    break;

                case OrderResult.ConfidenceDesc:
                    s = new SortDescriptor <Data.Smlouva>().Field(f => f.Field(ff => ff.ConfidenceValue).Descending());
                    break;

                case OrderResult.CustomerAsc:
                    s = new SortDescriptor <Data.Smlouva>().Field(f => f.Field(ff => ff.Platce.ico).Ascending());
                    break;

                case OrderResult.ContractorAsc:
                    s = new SortDescriptor <Data.Smlouva>().Field(f => f.Field("prijemce.ico").Ascending());
                    break;

                case OrderResult.LastUpdate:
                    s = new SortDescriptor <Data.Smlouva>().Field(f => f.Field("lastUpdate").Descending());
                    break;

                case OrderResult.ClassificationRelevance:
                    s = new SortDescriptor <Data.Smlouva>().Field(f => f.Field("classification.types.classifProbability").Descending());
                    break;

                case OrderResult.Relevance:
                default:
                    break;
                }

                return(s);
            }
Пример #19
0
            public static SmlouvaSearchResult CachedSimpleSearch(TimeSpan expiration,
                                                                 string query, int page, int pageSize, OrderResult order,
                                                                 bool?platnyZaznam = null, bool includeNeplatne = false,
                                                                 bool logError     = true, bool fixQuery        = true
                                                                 )
            {
                FullSearchQuery q = new FullSearchQuery()
                {
                    query           = query,
                    page            = page,
                    pageSize        = pageSize,
                    order           = order,
                    platnyZaznam    = platnyZaznam,
                    includeNeplatne = includeNeplatne,
                    logError        = logError,
                    fixQuery        = fixQuery
                };

                return(cachedSearches.Get(Newtonsoft.Json.JsonConvert.SerializeObject(q), expiration));
            }
Пример #20
0
 private static CompactResponse Send(Socket client, OrderResult ret)
 {
     try
     {
         if (client.Connected)
         {
             //傳回Response
             byte[] data = Encoding.UTF8.GetBytes(((int)ret).ToString());
             //寫入資料本體
             client.Send(new ArraySegment<byte>[]{
                             new ArraySegment<byte>(CompactResponse.HttpOK),
                             new ArraySegment<byte>(Encoding.UTF8.GetBytes(data.Length + "\r\n\r\n")),
                             new ArraySegment<byte>(data)}
                    );
             client.Shutdown(SocketShutdown.Both);
         }
     }
     catch (System.Exception ex)
     {
         LogWrapper.Error(ex);
     }
     return null;
 }
Пример #21
0
 /// <summary>
 /// Creates new instance.
 /// </summary>
 /// <param name="result">Order result.</param>
 public ProductOrderResult(OrderResult result)
 {
     Result = result;
 }
Пример #22
0
            public static OsobaSearchResult SimpleSearch(string query, int page, int pageSize, OrderResult order
                                                         , bool exactNumOfResults = false)
            {
                //fix without elastic
                if (page < 1)
                {
                    page = 1;
                }
                var takeNum = page * pageSize;

                if (takeNum > 100)
                {
                    takeNum = 100;
                }
                //elastik hyr

                List <Osoba> foundPepole = new List <Osoba>();

                string        regex     = @"osoba\w{0,13}:\s?(?<osoba>[\w-]{3,25})";
                List <string> peopleIds = Devmasters.RegexUtil.GetRegexGroupValues(query, regex, "osoba").ToList();
                long          total     = peopleIds.LongCount();

                if (peopleIds is null || peopleIds.Count == 0)
                {
                    var people = OsobyES.OsobyEsService.FulltextSearch(query, page, pageSize);
                    peopleIds = people.Results.Select(r => r.NameId).ToList();
                    total     = total + people.Total;
                }

                foreach (var id in peopleIds)
                {
                    var foundPerson = Osoba.GetByNameId(id);
                    if (foundPerson != null)
                    {
                        foundPepole.Add(foundPerson);
                    }
                    else
                    {
                        total = total - 1; // odecti neplatne osoby
                    }
                }

                var result = new OsobaSearchResult();

                result.Total          = total;
                result.Q              = query;
                result.ElasticResults = null; //TODO
                result.Results        = foundPepole;
                result.Page           = page;
                result.PageSize       = pageSize;
                result.Order          = order.ToString();
                result.IsValid        = true;
                return(result);
            }
Пример #23
0
        /// <summary>
        /// Message décrivant un acquitement
        /// </summary>
        public static String Ack(String _tester, OrderResult _data)
        {
            String message = "<MS><Type>Message</Type><Name>Ack</Name><Source>" + _tester + "</Source><Datas>" + _data + "</Datas></MS>";

            return(message);
        }
Пример #24
0
 protected void When_processing_an_order_with_a_negative_quantity()
 {
     _result = SUT.Process(new Order {
         PartNumber = "TestPart", Quantity = -1
     });
 }
Пример #25
0
        public OrderResult Order(string orderno, int orderamt, string notifyurl, string ordername, string openid, string ip, string attach)
        {
            //参考代码
            //http://blog.csdn.net/suixufeng/article/details/71215461


            var config = Config.XCX;


            string notifyUrl = notifyurl;


            string appid  = config.AppID;
            string mch_id = config.mch_id;

            string body = ordername; //商品描述


            string notify_url = notifyUrl;          //通知地址

            string spbill_create_ip = ip;           //终端IP

            string total_fee = orderamt.ToString(); //总金额,单位分


            //订单号
            string out_trade_no = orderno;


            var dic = new Dictionary <string, string>
            {
                { "appid", appid },
                { "mch_id", mch_id },
                { "nonce_str", GetRandomString(20) /*Random.Next().ToString()*/ },
                { "body", body },
                { "out_trade_no", out_trade_no },         //商户自己的订单号码
                { "total_fee", total_fee },
                { "spbill_create_ip", spbill_create_ip }, //服务器的IP地址
                { "notify_url", notify_url },             //异步通知的地址,不能带参数
                { "trade_type", "JSAPI" },
                { "attach", attach },
                { "openid", openid }
            };

            dic.Add("sign", GetSignString(dic, config.mch_secret));

            var sb = new StringBuilder();

            sb.Append("<xml>");
            foreach (var d in dic)
            {
                sb.Append("<" + d.Key + "><![CDATA[" + d.Value + "]]></" + d.Key + ">");
            }
            sb.Append("</xml>");


            string postXML = sb.ToString();



            var enc = Encoding.GetEncoding("UTF-8");

            string resultXML = null;

            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";

            using (var wc = new WebClient())
            {
                byte[] data = enc.GetBytes(postXML);

                byte[] result = wc.UploadData(url, data);

                if (result != null)
                {
                    resultXML = enc.GetString(result);
                }
            }

            if (string.IsNullOrEmpty(resultXML))
            {
                return(null);
            }


            var xml = new XmlDocument();

            xml.LoadXml(resultXML);

            if (xml == null)
            {
                return(null);
            }

            var orderResult = new OrderResult();

            string return_code = xml.SelectSingleNode("/xml/return_code").InnerText;

            if (return_code == "SUCCESS")
            {
                var dict = new Dictionary <string, string>();

                var nodes = xml.DocumentElement.ChildNodes;
                for (int i = 0; i < nodes.Count; i++)
                {
                    var node = nodes[i];
                    dict[node.Name] = node.InnerText;
                }


                if (dict["result_code"] == "SUCCESS")
                {
                    orderResult.Status = "SUCC";

                    var res = new Dictionary <string, string>
                    {
                        { "appId", config.AppID },
                        { "timeStamp", GetTimeStamp() },
                        { "nonceStr", dict["nonce_str"] },
                        { "package", "prepay_id=" + dict["prepay_id"] },
                        { "signType", "MD5" }
                    };

                    res.Add("paySign", GetSignString(res, config.mch_secret));

                    //在服务器上签名
                    orderResult.Data = res;
                }
            }

            return(orderResult);
        }