/// <summary> /// Вставляем данные по товару в бд и уведомляем об это пользователя /// </summary> /// <param name="Newprod"></param> private async void InsertToDb(ParseStruct Newprod) { Newprod.CategoryId = CategoryCheck(Newprod.CategoryName); //скачиваем файл с указанного ресурса var photo = await DownloadPhoto(Newprod.PhotoUrl); if (ProductCheck(Newprod.Name) > 0) { await SendMessage(new BotMessage { TextMessage = "Товар с таким название уже существует: " + Newprod.Name }); } if (Newprod.CategoryId > 0 && ProductCheck(Newprod.Name) == 0 && photo != null) { int ProductId = 0; Message message = new Message(); using (MemoryStream ms = new MemoryStream(photo)) { // Отправляем скачаную фотографию через бота. Тем самым загружаем ее на сервере телеграм message = await base.SendFileStream(Newprod.Name, ms); } if (message != null && message.Photo != null && message.Photo.Count() > 0) { var fs = InsertToAttachmentFs(photo); if (fs > 0) { ProductId = InsertNewProduct(Newprod); await InsertProductPhoto(ProductId, fs); var attach = InsertAttachment(fs, message.Photo[message.Photo.Length - 1].FileId); } } else { await SendMessage(new BotMessage { TextMessage = "Ошибка при отправки фотографии товара в телеграм: " + Newprod.Name }); } if (ProductId < 1) { await SendMessage(new BotMessage { TextMessage = "Не удалось добавить: " + Newprod.Name }); } } if (photo == null) { await SendMessage(new BotMessage { TextMessage = "Не удалось скачать фотографию: " + Newprod.Name }); } }
public void Parse(object data) { Type objtype = this.GetType(); Type datatype = data.GetType(); List <ParseStruct> all = new List <ParseStruct>(); FieldInfo[] datafields = datatype.GetFields(); for (int i = 0; i < datafields.Length; i++) { FieldInfo datafi = datafields[i]; object datav = datafi.GetValue(data); if (datav == null) { continue; } all.Add(new ParseStruct() { Name = datafi.Name, Type = datafi.FieldType, Value = datav }); } PropertyInfo[] dataproperties = datatype.GetProperties(); for (int i = 0; i < dataproperties.Length; i++) { PropertyInfo property = dataproperties[i]; object datav = property.GetValue(data); if (datav == null) { continue; } all.Add(new ParseStruct() { Name = property.Name, Type = property.PropertyType, Value = datav }); } for (int i = 0; i < all.Count; i++) { ParseStruct parseStruct = all[i]; FieldInfo objfi = objtype.GetField(parseStruct.Name); if (objfi == null || !typeof(IData).IsAssignableFrom(objfi.FieldType)) { continue; } bool isList = objfi.FieldType.IsGenericType && objfi.FieldType.GetGenericTypeDefinition() == typeof(ListData <>); bool isDict = objfi.FieldType.IsGenericType && objfi.FieldType.GetGenericTypeDefinition() == typeof(DictionaryData <>); bool isStruct = typeof(StructData).IsAssignableFrom(objfi.FieldType); bool isBase = objfi.FieldType.BaseType.IsGenericType && objfi.FieldType.BaseType.GetGenericTypeDefinition() == typeof(BaseData <>) && objfi.FieldType.BaseType.GetGenericArguments()[0] == parseStruct.Type; object objv = objfi.GetValue(this); if (objv != null) { if (isList) { (objv as IListData).ParseObject(parseStruct.Value); } else if (isDict) { (objv as IDictionaryData).ParseObject(parseStruct.Value); } else if (isStruct) { (objv as StructData).Parse(parseStruct.Value); } else if (isBase) { (objv as IBaseData).FastSetValue(parseStruct.Value); } } else { if (isList) { objfi.SetValue(this, ListData.Parse(objfi.FieldType.GetGenericArguments()[0], parseStruct.Value)); } else if (isDict) { objfi.SetValue(this, DictionaryData.Parse(objfi.FieldType.GetGenericArguments()[0], parseStruct.Value)); } else if (isStruct) { objfi.SetValue(this, StructData.Parse(objfi.FieldType, parseStruct.Value)); } else if (isBase) { objfi.SetValue(this, Activator.CreateInstance(objfi.FieldType, parseStruct.Value)); } } } }
/// <summary> /// Добавить новый товар в БД. /// </summary> /// <param name="Newprod">объект описывающий новый товар</param> /// <returns>Возращает Id</returns> private int InsertNewProduct(ParseStruct Newprod) { using (MarketBotDbContext db = new MarketBotDbContext()) { try { Product InsertNewProduct = new Product { Name = Newprod.Name, CategoryId = Newprod.CategoryId, TelegraphUrl = Newprod.NoteUrl, Text = Newprod.Desc, DateAdd = DateTime.Now, PhotoId = Newprod.PhotoId, Enable = true, UnitId = Newprod.UnitId }; db.Product.Add(InsertNewProduct); if (db.SaveChanges() > 0) { ProductPrice productPrice = new ProductPrice { ProductId = InsertNewProduct.Id, DateAdd = DateTime.Now, Enabled = true, Value = Newprod.Price, CurrencyId = Newprod.CurrencyId, Volume = 1 }; Stock stock = new Stock { ProductId = InsertNewProduct.Id, Balance = Newprod.StockBalance, DateAdd = DateTime.Now, Quantity = Newprod.StockBalance }; db.Stock.Add(stock); db.ProductPrice.Add(productPrice); db.SaveChanges(); return(InsertNewProduct.Id); } else { return(-1); } } catch { return(-1); } } /// <summary> /// импортируем данные из csv файла в бд /// </summary> /// <param name="id">id файлан на серевере Телегарм</param> /// <returns></returns> }
/// <summary> /// Парсим CSV файл /// </summary> /// <param name="CSV"></param> /// <returns></returns> private async Task <List <ParseStruct> > ParseCSV(Stream CSV) { List <string> rows = new List <string>(); List <ParseStruct> ListParse = new List <ParseStruct>(); try { StreamReader sr = new StreamReader(CSV, Encoding.GetEncoding(1251)); while (sr.Peek() >= 0) { rows.Add(await sr.ReadLineAsync()); } sr.Close(); sr.Dispose(); for (int i = 1; i < rows.Count; i++) { string[] split = rows[i].Split(';'); ParseStruct parseStruct = new ParseStruct(); if (split != null && split[0] != "") // Название { parseStruct.Name = split[0]; } else { throw new Exception("Не удалось определить навзание товара"); } if (split != null && split.Length > 2 && split[2] != "") // Категория { parseStruct.CategoryName = split[2]; } else { throw new Exception("Не удалось определить категорию товара"); } if (split != null && split.Length > 1) // Цена { parseStruct.Price = Convert.ToDouble(split[1]); } else { throw new Exception("Не удалось определить стоимость товара"); } if (split != null && split.Length > 2) // проверяем есть ли описание { parseStruct.Desc = split[3]; } if (split != null && split.Length > 3) // проверяем есть ли ссылка на заметку //проверяем есть ли ссылка на файл фотографии. Если есть то скаичваем, отправляем боту, получаем FileId { if (split.Length > 4 && split[5] != null && split[5].Contains(".jpg") || split.Length > 4 && split[5] != null && split[5].Contains(".png")) { parseStruct.PhotoUrl = split[5]; } } //Остаток if (split.Length > 5 && split[6] != null) { parseStruct.StockBalance = Convert.ToInt32(split[6]); } else if (parseStruct.StockBalance < 0) { parseStruct.StockBalance = 0; } else { parseStruct.StockBalance = 0; } //Валюта if (split.Length > 6 && split[7] != null) { parseStruct.CurrencyId = CurrencyCheck(split[7]); } else // Если валюта не указана { parseStruct.CurrencyId = 1; } if (split.Length > 7 && split[8] != null) { parseStruct.UnitId = UnitCheck(split[8]); } else { parseStruct.UnitId = 1; } ListParse.Add(parseStruct); } return(ListParse); } catch { return(null); } }