Форум программистов, компьютерный форум, киберфорум
C#: ASP.NET Core
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.57/47: Рейтинг темы: голосов - 47, средняя оценка - 4.57
0 / 0 / 0
Регистрация: 09.12.2015
Сообщений: 19
1

Input string was not in a correct format

17.01.2017, 22:56. Показов 9840. Ответов 15
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Добрый вечер!
Хотел бы узнать в чем может быть ошибка загрузки прайс листа
Скрин приложен ниже
вот код:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using CsvHelper;
using CsvHelper.Configuration;
using DetalBmw;
using DetalBmw.Models;
using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Bmw;
using Nop.Core.Domain.Catalog;
using Nop.Data;
using Nop.Services.Catalog;
using Nop.Services.Logging;
using Nop.Services.Security;
 
namespace Nop.Admin.Controllers
{
    public class DetalBMWController : BaseAdminController
    {
        public const int BATCH_SIZE = 3000;
        public const int BMW_CATEGORY_ID = 17;
        public const int MAX_IMPORT_SIZE = 500000;
 
        private IProductService _productService;
        private ICategoryService _categoryService;
        private IPermissionService _permissionService;
        private IRepository<BmwProduct> _bmwProductRepository;
        private IRepository<Product> _productRepository;
        private ILogger _logger;
 
 
        public DetalBMWController(IProductService productService
            , ICategoryService categoryService
            , ILogger logger
            , IPermissionService permissionService
            , IRepository<BmwProduct> bmwProductRepository
            , IRepository<Product> productRepository
            )
        {
            _productService = productService;
            _categoryService = categoryService;
            _permissionService = permissionService;
            _logger = logger;
            _bmwProductRepository = bmwProductRepository;
            _productRepository = productRepository;
        }
 
        public ActionResult Index()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
                return AccessDeniedView();
 
            return View();
        }
 
        [HttpPost]
        public ActionResult UploadPrice(HttpPostedFileBase pricelist)
        {
            if (pricelist.ContentLength > 0)
            {
                var category = _categoryService.GetCategoryById(BMW_CATEGORY_ID);
                var priceItems = GetPriceItems(pricelist.InputStream);
 
                _logger.Information("load all products");
                var allProducts = _productService.GetProductsByCategoryId(BMW_CATEGORY_ID)
                    .OrderBy(x => x.Sku)
                    .ToArray();
                _logger.Information("loaded products " + allProducts.Count());
 
                var productsToInsert = new List<Product>();
                var productsToUpdate = new List<Product>();
 
                _logger.Information("total items " + priceItems.Count());
 
                var allProductsMap = allProducts.ToDictionary(x => x.Sku, x => x);
                int i = 0;
                foreach (var item in priceItems)
                {
                    i++;
                    Product product;
                    if (allProductsMap.TryGetValue(SparePart.GetSku(item.Code), out product))
                    {
                        if (item.Count != product.StockQuantity
                                                   || item.Price != product.Price
                                                   || item.Price4Days != product.PriceStock
                                                   || item.PriceFast != product.PriceFastStock)
                        {
                            productsToUpdate.Add(UpdateProduct(product, item.Title, item.Count, item.Price, item.Price4Days, item.PriceFast));
                        }
                    }
                    else
                        productsToInsert.Add(CreateProduct(category, SparePart.GetSku(item.Code), item.Title, item.Count, item.Price, item.Price4Days, item.PriceFast));
 
                    if (productsToInsert.Count >= BATCH_SIZE)
                    {
                        _logger.Information($"insert products {productsToInsert.Count}");
                        _productRepository.AddRange(productsToInsert);
                        productsToInsert.Clear();
                    }
 
                    if (productsToUpdate.Count >= BATCH_SIZE)
                    {
                        _logger.Information($"update products {productsToUpdate.Count}");
                        _productRepository.Update(productsToUpdate);
                        productsToUpdate.Clear();
                    }
                }
                _productRepository.AddRange(productsToInsert);
                _productRepository.Update(productsToUpdate);
 
                _logger.Information("price update completed");
            }
 
            return View();
        }
 
        private void UploadProducts(IEnumerable<PriceItem> priceItems)
        {
            var first = priceItems.First();
            var bmwProducts = priceItems.Select(x => new BmwProduct()
            {
                CreatedOnUtc = DateTime.UtcNow,
                Price = x.Price,
                PriceFastStock = x.PriceFast,
                PriceStock = x.Price4Days,
                Sku = x.Code
            }).ToArray();
 
            foreach (var chunk in bmwProducts.Chunk(1000))
            {
                _bmwProductRepository.Insert(chunk);
                _bmwProductRepository.Detach(chunk.ToArray());
            }
        }
 
        private static Product CreateProduct(Nop.Core.Domain.Catalog.Category category, string sku, string title, int amount, decimal price, decimal priceStock, decimal priceFastStock)
        {
            var product = new Product
            {
                Price = price,
                Sku = sku,
                Name = title,
                CreatedOnUtc = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow,
                Published = true,
                ProductType = ProductType.SimpleProduct,
                StockQuantity = amount,
                OrderMinimumQuantity = 1,
                OrderMaximumQuantity = amount,
                CustomerEntersPrice = true,
                MinimumCustomerEnteredPrice = 0,
                MaximumCustomerEnteredPrice = int.MaxValue,
                PriceStock = priceStock,
                PriceFastStock = priceFastStock,
                VisibleIndividually = true,
                IsShipEnabled = false,
 
            };
            product.ProductCategories.Add(new ProductCategory { Category = category, Product = product });
 
            return product;
        }
 
        public static Product UpdateProduct(Product product, string title, int amount, decimal price, decimal priceStock, decimal priceFastStock)
        {
            product.Price = price;
            product.Name = title;
            product.UpdatedOnUtc = DateTime.UtcNow;
            product.StockQuantity = amount;
            product.Deleted = false;
            product.PriceStock = priceStock;
            product.PriceFastStock = priceFastStock;
            product.CustomerEntersPrice = true;
            product.MinimumCustomerEnteredPrice = 0;
            product.MaximumCustomerEnteredPrice = int.MaxValue;
            product.OrderMaximumQuantity = amount;
            product.OrderMinimumQuantity = 1;
 
            return product;
        }
 
        public void CreateOrUpdateProduct(ProductCategory category, string sku, string title, int amount, decimal price)
        {
 
            var product = _productService.GetProductBySku(sku);
            if (product == null)
            {
                product = new Product
                {
                    Price = price,
                    Sku = sku,
                    Name = title,
                    CreatedOnUtc = DateTime.UtcNow,
                    UpdatedOnUtc = DateTime.UtcNow,
                    Published = true,
                    ProductType = ProductType.SimpleProduct,
                    StockQuantity = amount,
                    OrderMinimumQuantity = 1
                };
                product.ProductCategories.Add(category);
                _productService.InsertProduct(product);
            }
            else
            {
                product.Price = price;
                product.Name = title;
                product.UpdatedOnUtc = DateTime.UtcNow;
                product.StockQuantity = amount;
                _productService.UpdateProduct(product);
            }
        }
 
        private static int ConvertToInt(string number)
        {
            number = number.Replace(",", "").Replace(".", "");
            return int.Parse(number);
        }
 
        private static decimal ConvertToDecimal(string number)
        {
            var ns = CultureInfo.CurrentCulture.NumberFormat;
            ns.NumberDecimalSeparator = ".";
 
            return decimal.Parse(number, ns);
        }
 
        private static IEnumerable<PriceItem> GetPriceItems(Stream stream)
        {
            int total = 0;
            var result = new List<PriceItem>();
            var ns = CultureInfo.CurrentCulture.NumberFormat;
            ns.NumberDecimalSeparator = ".";
 
            bool skipFirstLine = true;
 
            var cp1251 = Encoding.GetEncoding(1251);
 
            var csvConfig = new CsvConfiguration();
            csvConfig.Encoding = Encoding.GetEncoding("windows-1251");
 
            using (var streamReader = new StreamReader(stream, csvConfig.Encoding))
            {
                using (var reader = new CsvReader(streamReader, csvConfig))
                {
                    while (reader.Read())
                    {
                        if (skipFirstLine)
                        {
                            skipFirstLine = false;
                            continue;
                        }
 
                        var item = new PriceItem();
 
                        item.Code = reader.GetField(0);
                        item.Title = reader.GetField(1);
                        //item.Title = Encoding.Default.GetString(csvConfig.Encoding.GetBytes(item.Title));
 
                        item.Count = ConvertToInt(reader.GetField(2));
                        item.Price = ConvertToDecimal(reader.GetField(4));
                        item.Price4Days = ConvertToDecimal(reader.GetField(5));
                        item.PriceFast = ConvertToDecimal(reader.GetField(6));
 
                        result.Add(item);
 
                        total++;
 
                        if (total == MAX_IMPORT_SIZE)
                            break;
                    }
                }
                /*
                while (!streamReader.EndOfStream)
                {
                    var line = streamReader.ReadLine();
                    if (skipFirstLine)
                    {
                        skipFirstLine = false;
                        continue;
                    }
                    var values = line.Split(',');
                    
                    var item = new PriceItem();
                    
                    item.Code = values[0];
                    item.Title = values[1];
                    item.Count = int.Parse(values[2]);
 
                    item.Price = decimal.Parse(values[4], ns);
                    item.Price4Days = decimal.Parse(values[5], ns);
                    item.PriceFast = decimal.Parse(values[6], ns);
 
                    result.Add(item);
                    total++;
                    if (total >= MaxCount)
                    {
                        break;
                    }
                }
                */
            }
 
            return result.OrderBy(x => x.Code).ToArray();
        }
    }
 
    public class PriceItem
    {
        public string Code { get; set; }
        public decimal Price { get; set; }
        public decimal Price4Days { get; set; }
        public decimal PriceFast { get; set; }
        public string Title { get; set; }
        public int Count { get; set; }
 
    }
}
Миниатюры
Input string was not in a correct format  
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
17.01.2017, 22:56
Ответы с готовыми решениями:

Input string was not in a correct format
Есть программка, простенькая - начисление заработной платы. сам код: private void...

Input string was not in a correct format
string data = MyDLL.MyDLL.giveOnlyData(); string input = &quot;1&lt;/td&gt;&lt;td&gt;(/d+,/d+)&quot;; ...

Mscorlob Input string was not in a correct format
Всем доброго дня. Вот всплыла проблема и я не знаю как ее решить. Возможно надо прописать...

Ошибка System.FormatException: Input string was not in a correct format
Разбираю пример из Шилдта, но он у меня почему-то не компиллируется: выдает ошибку...

15
Администратор
Эксперт .NET
17019 / 13372 / 5217
Регистрация: 17.03.2014
Сообщений: 27,342
Записей в блоге: 1
17.01.2017, 23:17 2
ecl1ps1s, судя по всему что-то не так со значением в колонке номер 3. Там ожидается int, а по факту что-то другое.
0
0 / 0 / 0
Регистрация: 09.12.2015
Сообщений: 19
17.01.2017, 23:45  [ТС] 3
OwenGlendower, Ну вот сам прайс
0
0 / 0 / 0
Регистрация: 09.12.2015
Сообщений: 19
17.01.2017, 23:46  [ТС] 4
OwenGlendower,
Вложения
Тип файла: xls наличие.xls (26.5 Кб, 7 просмотров)
0
Администратор
Эксперт .NET
17019 / 13372 / 5217
Регистрация: 17.03.2014
Сообщений: 27,342
Записей в блоге: 1
17.01.2017, 23:57 5
ecl1ps1s, это файл Excel. Код расчитан на работу с текстовыми CSV файлами.
0
0 / 0 / 0
Регистрация: 09.12.2015
Сообщений: 19
18.01.2017, 01:04  [ТС] 6
OwenGlendower, Я все это понимаю, но ошибку он выдает)

Добавлено через 1 минуту
я как раз,пытаюсь загрузить это все в формате csv, но он ругается, как я понял на порядок, я перебрал эти порядки, но так и не понял, в чем ошибка последовательности
0
Администратор
Эксперт .NET
17019 / 13372 / 5217
Регистрация: 17.03.2014
Сообщений: 27,342
Записей в блоге: 1
18.01.2017, 01:16 7
ecl1ps1s, давай тогда взглянем на csv файл который ты загружаешь
0
0 / 0 / 0
Регистрация: 09.12.2015
Сообщений: 19
18.01.2017, 01:21  [ТС] 8
OwenGlendower,
Вложения
Тип файла: rar price.rar (248 байт, 2 просмотров)
0
Администратор
Эксперт .NET
17019 / 13372 / 5217
Регистрация: 17.03.2014
Сообщений: 27,342
Записей в блоге: 1
18.01.2017, 01:39 9
ecl1ps1s, возможно разделитель колонок неправильный. Попробуй запятую или табуляцию. Что точно неверно - порядок колонок. Судя по коду порядок должен быть таким: Code, Title, Count, ???, Price, Price4Days, PriceFast. В CSV файле который ты выложил порядок другой: Code, Price, Price4Days, PriceFast, Title, Count. Еще в качестве разделителя целой и дробной части ожидается точка, а не запятая. Исправь все эти ошибки и попробуй еще раз загрузить.
0
0 / 0 / 0
Регистрация: 09.12.2015
Сообщений: 19
18.01.2017, 01:58  [ТС] 10
OwenGlendower, Теперь такая ошибка, ниже файл csv с поправками
Миниатюры
Input string was not in a correct format  
Вложения
Тип файла: rar newprice.rar (276 байт, 2 просмотров)
0
0 / 0 / 0
Регистрация: 09.12.2015
Сообщений: 19
18.01.2017, 02:03  [ТС] 11
а с точкой появляется изначальная ошибка
0
Эксперт .NET
12078 / 8387 / 1281
Регистрация: 21.01.2016
Сообщений: 31,601
18.01.2017, 06:20 12
ecl1ps1s, есть какая-то объективная причина не пользоваться отладчиком для поиска причины сбоя?..
0
0 / 0 / 0
Регистрация: 09.12.2015
Сообщений: 19
18.01.2017, 13:46  [ТС] 13
Usaga, ну все тесты удачные, без ошибок
0
Эксперт .NET
12078 / 8387 / 1281
Регистрация: 21.01.2016
Сообщений: 31,601
18.01.2017, 13:51 14
ecl1ps1s, причём здесь тесты. Я имею в виду запустить веб-приложение в студии (Visual Studio) в режиме отладки (Debug) и своими глазами посмотреть на место, где происходит ошибка и на данные, которые в тот момент там крутятся. Это будет быстрее и вернее, чем сидеть и гадать, что может быть не так.
0
0 / 0 / 0
Регистрация: 09.12.2015
Сообщений: 19
19.01.2017, 18:19  [ТС] 15
Usaga, Да дело в табуляции было, но теперь другая проблемка. Он пишет, что все обновил, но значения не меняет. Это может быть из-за того, что например, неправильно записывает в базу или вообще не подключается к ней?
0
Администратор
Эксперт .NET
17019 / 13372 / 5217
Регистрация: 17.03.2014
Сообщений: 27,342
Записей в блоге: 1
19.01.2017, 18:40 16
ecl1ps1s, и снова тебе поможет отладчик. Установи точку остановки на строки
C#
1
2
               _productRepository.AddRange(productsToInsert);
                _productRepository.Update(productsToUpdate);
в методе UploadPrice и посмотри что находится в коллекциях productsToInsert и productsToUpdate. Исходя из того что увидишь думай дальше.
0
19.01.2017, 18:40
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
19.01.2017, 18:40
Помогаю со студенческими работами здесь

Ошибка времени выполнения: Input string was not in a correct format
Добрый день! Не могу понять, в чем ошибка( Пишет: спорт.pas(44) : Ошибка времени выполнения: Input...

Ошибка: System.FormatException: "Input string was not in a correct format."
Помогите когда в компиляторе ввожу 3 после: if (page == 1) { ...

Выдает ошибку "Input string was not in a correct format."
Нужно чтобы при вводе массива прорабатывал оба типа(int,string), но при запуске выдает ошибку ...

Ошибка "Input string was not in a correct format" при приобразовании double
using System; namespace MS_ACCESS_ADO.NET { public static class ConsoleReader { ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
16
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru