An error I encountered while getting a json file - asp.net

I need to pull a json file on the remote server.I leave the link of the file here.
turkmedya.com.tr/anasayfa.json
I also share the open version of the json file as a photo.enter image description here
I also have to pull the categories from the file. Can you give me a hand?
Anasayfa.cs
public class data
{
public string sectionType { get; set; }
public string titleBgColor { get; set; }
public IList<veri> itemList { get; set; }
}
public class veri
{
public string shortText { get; set; }
public string fullPath { get; set; }
public string itemId { get; set; }
public string imageUrl { get; set; }
}
public class cat
{
public string categoryId { get; set; }
public string Title{ get; set; }
}
public class ListJson
{
public string errorMessage { get; set; }
public IList<data> data { get; set; }
public IList<cat> category { get; set; }
}
HomeController.cs
public ActionResult Index()
{
string url = #"http://turkmedya.com.tr/anasayfa.json";
string jsonVerisi = "";
try
{
using (WebClient response = new WebClient())
{
jsonVerisi = response.DownloadString(url);
}
ListJson account = JsonConvert.DeserializeObject<ListJson>(jsonVerisi);
foreach (var list in account.data)
{
System.Console.WriteLine(list.ToString());
ViewBag.ca = list.itemList.ToList();
var a = account.data.Count;
var b = list.itemList.Count;
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return View();
}

Related

Adding a list of objects to SQL Server - ASP.NET Web API

I'm trying to add a list of objects to a SQL Server database via Entity Framework but I get an error with Add
[HttpPost]
public void Post(List<Row> rows)
{
try
{
using (DbModel dbModel = new DbModel())
{
foreach (var el in rows)
{
dbModel.Provider_Status.Add(el);
}
dbModel.SaveChanges();
}
}
catch { }
}
Row class:
public class Row
{
public string FileName { get; set; }
public string FileTitle { get; set; }
public string ProviderID { get; set; }
public string ServiceID { get; set; }
public string PublishDate { get; set; }
public string ExpiryDate { get; set; }
}
Database Model DbModel:
public partial class Provider_Status
{
public int Id { get; set; }
public string FileName { get; set; }
public string FileTitle { get; set; }
public string ProviderID { get; set; }
public string ServiceID { get; set; }
public string PublishDate { get; set; }
public string ExpiryDate { get; set; }
}
Error Message:
CS1503 Argument 1: cannot convert from 'File_Upload.Models.Row' to 'File_Upload.Models.Provider_Status
Your DbModel defines a data set of type Provider_Status - so if you want to add data to this data set, you need to provide Provider_Status objects - not Row objects (as you do now).
You need to convert those Row object to Provider_Status - try something like this:
[HttpPost]
public void Post(List<Row> rows)
{
try
{
using (DbModel dbModel = new DbModel())
{
foreach (var el in rows)
{
// create a new "Provider_Status" object, based on the
// "Row" values being passed in
Provider_Status status = new Provider_Status
{
FileName = el.FileName
FileTitle = el.FileTitle
ProviderID = el.ProviderID
ServiceID = el.ServiceID
PublishDate = el.PublishDate
ExpiryDate = el.ExpiryDate
};
// add that new Provider_Status object to your dbModel
dbModel.Provider_Status.Add(status);
}
dbModel.SaveChanges();
}
}
catch { }
}

How to save data in many to many relation without duplicate in my Card table [Entity Framework]

I have a problem. I cannot save cards without duplicates.
I have 3 tables a Deck, Card table and a CardDeck table which is the junction table.
The goal is to store a deck in the database without the cards being duplicated.
Table Card
namespace MTG_Deck.Models
{
public class Card
{
[Key]
public int CardId { get; set; }
public string Name { get; set; }
public string Text { get; set; }
public string Type { get; set; }
public string SetName { get; set; }
public string Artist { get; set; }
public string ManaCost { get; set; }
public string Rarity { get; set; }
public string ImageUrl { get; set; }
public string Toughness { get; set; }
public string Power { get; set; }
public string id { get; set; }
public virtual ICollection<DeckCard> Decks { get; set; }
}
}
Table Deck
namespace MTG_Deck.Models
{
public class Deck
{
[Key]
public int DeckId { get; set; }
[Required]
public string Name { get; set; }
[DataType(DataType.Date)]
public DateTime CreateAt { get; set; }
public User User { get; set; }
public virtual ICollection<DeckCard> Cards { get; set; }
}
}
Table CardDeck
namespace MTG_Deck.Models
{
public class DeckCard
{
public int DeckID { get; set; }
public int CardID { get; set; }
public Deck Deck { get; set; }
public Card Card { get; set; }
}
}
CardDeckRequest contains the content of the request.
namespace MTG_Deck.Models
{
public class CardDeckRequest
{
[Required]
public int UserID { get; set; }
[Required]
public string Token { get; set; }
[Required]
public Deck Deck { get; set; }
[Required]
[MinLength(5, ErrorMessage = "The deck must contain 60 cards.")]
public List<Card> Cards { get; set; }
}
}
Controller
[HttpPost]
public IActionResult Add([FromBody] CardDeckRequest request)
{
User user = _context.User.Where(u => u.Token == request.Token).FirstOrDefault<User>();
if (user == null) {
var error = new string[] {"You have to be connected to create a deck!"};
BadRequest(new { errors = new { success = error } });
}
List<DeckCard> deckList = new List<DeckCard>();
if (ModelState.IsValid) {
request.Deck.User = user;
foreach (var item in request.Cards)
{
Card card = _context.Card.FirstOrDefault(c => c.Name == item.Name);
if (card == null) {
card = item;
Console.WriteLine("coucou");
}
DeckCard deckCard = new DeckCard {
Card = card,
Deck = request.Deck
};
deckList.Add(deckCard);
}
_context.DeckCard.AddRange(deckList);
_context.SaveChanges();
var error = new string[] {"Your deck has been successfully saved."};
return Ok(new { errors = new { success = error } });
}
return BadRequest(ModelState.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
));
}

Unable to store images to database

The following code below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Car model, HttpPostedFileBase file)
{
var currentUser = UserManager.FindById(User.Identity.GetUserId());
var user = this.db.Users.Where(u => u.Id == currentUser.Id).FirstOrDefault();
if(ModelState.IsValid)
{
if (file != null && file.ContentLength > 0)
{
var photo = new FilePath
{
FileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName),
FileType = FileType.Photo
};
model.FilePaths = new List<FilePath>();
model.FilePaths.Add(photo);
file.SaveAs(Path.Combine(Server.MapPath("~/Images/"), photo.FileName));
}
user.Cars.Add(model);
db.SaveChanges();
return RedirectToAction("Default", "Home");
}
SetCategoryViewBag(model.Category.CategoryId);
return View(model);
}
Won't let me to store any images to the database. The image table doesn't store any information at all. However, the cars table is ok, but images is still showing as null.
What have I done wrong here?
Edit:
Car model:
public class Car
{
[Key]
public int CarId { get; set; }
public string Title { get; set; }
public int Price { get; set; }
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
public virtual ICollection<FilePath> FilePaths { get; set; }
}
FilePath model:
public class FilePath
{
public int FilePathId { get; set; }
[StringLength(255)]
public string FileName { get; set; }
public FileType FileType { get; set; }
public int CarId { get; set; }
public virtual Car Cars { get; set; }
}

Parse Complex JSON to ASP.NET MVC 3 using jQuery

I have to post this javascript object to asp.net controller:
The model in server side is:
public class UserExperience
{
public class competences
{
public string id { get; set; }
public string level { get; set; }
public string name { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
public long id { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string projectName { get; set; }
public string company { get; set; }
public string customerIndustry { get; set; }
public string jobTitle { get; set; }
public string projectDescription { get; set; }
public string responsabilities { get; set; }
public List<competences> competence { get; set; }
public List<int> deletedCompetences { get; set; }
public bool isNew { get; set; }
public bool isSaved { get; set; }
}
I tried to send the json like this:
$.ajax("/candidate/saveUserExperience", {
data : JSON.stringify({ue: is.Candidate.BO.userExperience[id]}),
//dataType: "text",
contentType : "application/json",
type : 'POST'
})
And this is the controller where I receive it:
public JsonResult saveUserExperience(UserExperience ue)
{
bool success;
success = true;
return Json(new { success, ue }, JsonRequestBehavior.AllowGet);
}
And I receive a null object.
I tried to do with:
UserExperience userExperience = new JavaScriptSerializer().Deserialize<UserExperience>(ue);
and I do not receive the competence subclass object.
Is there a solution to this problem ?
Thanks.
Why are you trying to pass is.Candidate.BO.userExperience[id] when you expect UserExperience object? Just write data: ue in ajax call parameters,

Insert multiple values from text box to the data base using the list<string>

This is the required image, I want to insert multiple value through Name, Employee Code and E-mail Id, by submit button which is in this page.
My database contains following field Id(primary key),Name (varchar 50),Employee Code (varchar 50), E-mail Id (varchar 50).
In the data layer, I code as following:
public static bool AddParticipantlistemployeecode(DimensionQuestion dimension)
{
bool result;
using (var helper = new DbHelper())
{
_cmdtext = "sp_NewGeneratedUniqueCode";
var success = new SqlParameter("#Success", SqlDbType.Bit, 1, ParameterDirection.Output, true, 0, 0,
"Result", DataRowVersion.Default, 0);
foreach (string s in dimension.CandidateName)
{
if (s.Trim().Length > 0)
{
var parameter = new[]
{
// new SqlParameter("#CompanyName",dimension.CompanyName ),
new SqlParameter("#CandidateName",s ),
new SqlParameter("#EmployeeCode",s ),
new SqlParameter("#EmailId",s ),
success,
};
helper.ExecuteScalar(_cmdtext, CommandType.StoredProcedure, parameter);
}
}
result = (bool)success.Value;
}
return result;
}
In the Model layer:
using System.Text;
using System.Collections.Generic;
namespace Cengrow.Survey.Core.Model
{
public class DimensionQuestion
{
public string CompanyName { get; set; }
// public string DimensionNumber { get; set; }
public List<string> CandidateName { get; set; }
public List<string> EmployeeCode { get; set; }
public List<string> EmailId { get; set; }
public int DimensionName { get; set; }
public string Section { get; set; }
//public string Rating { get; set; }
public List<string> Questions { get; set; }
//public string Question2 { get; set; }
//public string Question3 { get; set; }
//public string Question4 { get; set; }
//public string Question5 { get; set; }
//public string Question6 { get; set; }
//public string Question7 { get; set; }
//public string Question8 { get; set; }
//public string Question9 { get; set; }
//public string Question10 { get; set; }
//public string Question11 { get; set; }
//public string Question12 { get; set; }
//public string Question13 { get; set; }
//public string Question14 { get; set; }
//public string Question15 { get; set; }
}
}
And finally in the business logic on the button click:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
FillObjects();
//if (InsertData.InsertCandidateCompany(_CandidateCompanyInformation ))
if (InsertData.AddParticipantlistemployeecode(_DimensionQuestion))
{
ShowMessage("Information is saved");
//Reset();
}
else
{
ShowMessage("Please try again");
}
}
finally
{
_DimensionQuestion = null;
}
}
private void FillObjects()
{
List<string> sp = new List<string>();
_DimensionQuestion = new Cengrow.Survey.Core.Model.DimensionQuestion();
// _DimensionQuestion.CompanyName = txtCompanyName.Text.Trim();
sp.Add(txtName1.Text.Trim());
sp.Add(txtName2.Text.Trim());
sp.Add(txtName3.Text.Trim());
sp.Add(txtName4.Text.Trim());
sp.Add(txtName5.Text.Trim());
sp.Add(txtName6.Text.Trim());
sp.Add(txtName7.Text.Trim());
sp.Add(txtName8.Text.Trim());
sp.Add(txtName9.Text.Trim());
sp.Add(txtName10.Text.Trim());
sp.Add(txtName11.Text.Trim());
sp.Add(txtName12.Text.Trim());
sp.Add(txtName13.Text.Trim());
sp.Add(txtName14.Text.Trim());
sp.Add(txtName15.Text.Trim());
sp.Add(txtName16.Text.Trim());
sp.Add(txtName17.Text.Trim());
sp.Add(txtName18.Text.Trim());
sp.Add(txtName19.Text.Trim());
sp.Add(txtName20.Text.Trim());
sp.Add(txtName21.Text.Trim());
sp.Add(txtName22.Text.Trim());
sp.Add(txtName23.Text.Trim());
sp.Add(txtName24.Text.Trim());
sp.Add(txtName25.Text.Trim());
_DimensionQuestion.CandidateName = sp;
sp.Add(txtEmployeeCode1.Text.Trim());
sp.Add(txtEmployeeCode2.Text.Trim());
sp.Add(txtEmployeeCode3.Text.Trim());
sp.Add(txtEmployeeCode4.Text.Trim());
sp.Add(txtEmployeeCode5.Text.Trim());
sp.Add(txtEmployeeCode6.Text.Trim());
sp.Add(txtEmployeeCode7.Text.Trim());
sp.Add(txtEmployeeCode8.Text.Trim());
sp.Add(txtEmployeeCode9.Text.Trim());
sp.Add(txtEmployeeCode10.Text.Trim());
sp.Add(txtEmployeeCode11.Text.Trim());
sp.Add(txtEmployeeCode12.Text.Trim());
sp.Add(txtEmployeeCode13.Text.Trim());
sp.Add(txtEmployeeCode14.Text.Trim());
sp.Add(txtEmployeeCode15.Text.Trim());
sp.Add(txtEmployeeCode16.Text.Trim());
sp.Add(txtEmployeeCode17.Text.Trim());
sp.Add(txtEmployeeCode18.Text.Trim());
sp.Add(txtEmployeeCode19.Text.Trim());
sp.Add(txtEmployeeCode20.Text.Trim());
sp.Add(txtEmployeeCode21.Text.Trim());
sp.Add(txtEmployeeCode22.Text.Trim());
sp.Add(txtEmployeeCode23.Text.Trim());
sp.Add(txtEmployeeCode24.Text.Trim());
sp.Add(txtEmployeeCode25.Text.Trim());
_DimensionQuestion.EmployeeCode = sp;
sp.Add(TextBox1.Text.Trim());
sp.Add(TextBox2.Text.Trim());
sp.Add(TextBox3.Text.Trim());
sp.Add(TextBox4.Text.Trim());
sp.Add(TextBox5.Text.Trim());
sp.Add(TextBox6.Text.Trim());
sp.Add(TextBox7.Text.Trim());
sp.Add(TextBox8.Text.Trim());
sp.Add(TextBox9.Text.Trim());
sp.Add(TextBox10.Text.Trim());
sp.Add(TextBox11.Text.Trim());
sp.Add(TextBox12.Text.Trim());
sp.Add(TextBox13.Text.Trim());
sp.Add(TextBox14.Text.Trim());
sp.Add(TextBox15.Text.Trim());
sp.Add(TextBox16.Text.Trim());
sp.Add(TextBox17.Text.Trim());
sp.Add(TextBox18.Text.Trim());
sp.Add(TextBox19.Text.Trim());
sp.Add(TextBox20.Text.Trim());
sp.Add(TextBox21.Text.Trim());
sp.Add(TextBox22.Text.Trim());
sp.Add(TextBox23.Text.Trim());
sp.Add(TextBox24.Text.Trim());
sp.Add(TextBox25.Text.Trim());
_DimensionQuestion.EmailId = sp;
}
The data is not coming proper into the database
You are adding the same value to all three parameters:
new SqlParameter("#CandidateName",s ),
new SqlParameter("#EmployeeCode",s ),
new SqlParameter("#EmailId",s
In all cases you are adding "s" which is CandidateName.
Edit: Candidate should be a class:
public class Candidate
{
public string Name { get; set; }
public string EmployeeCode { get; set; }
public string Email { get; set; }
public Candidate(string name, string code, string email)
{
this.Name = name;
this.EmployeeCode = code;
this.Email = email;
}
}
Then your DimensionQuestion should contain a
List<Candidate> Candidates
instead of
public List<string> CandidateName { get; set; }
public List<string> EmployeeCode { get; set; }
public List<string> EmailId { get; set; }
Then you FillObjects method add Candidate objects to the Candidates list
Candidates.Add(new Candidate(txtName1.Text.Trim(),
txtEmployeeCode1.Text.Trim(),
TextBox1.Text.Trim()));
Candidates.Add(new Candidate(txtName2.Text.Trim(),
txtEmployeeCode2.Text.Trim(),
TextBox2.Text.Trim()));
Finaly your data layer should be:
foreach (Candidate candidate in dimension.Candidates)
{
if (!String.IsNullOrEmpty(candidate.Name))
{
var parameter = new[]
{
// new SqlParameter("#CompanyName",dimension.CompanyName ),
new SqlParameter("#CandidateName",candidate.Name ),
new SqlParameter("#EmployeeCode",candidate.Code ),
new SqlParameter("#EmailId",candidate.Email ),
success,
};
helper.ExecuteScalar(_cmdtext, CommandType.StoredProcedure, parameter);
}
}

Resources