NEST - can not index an object (c# search) - c#

I grabbed the latest NuGet of NEST and tried to implement simple elastic search. My code do not index an object. IsValid returns false but I have no idea why. Result is also empty.
Here is my snippet of code. I'll be grateful for the help.
public ActionResult Search()
{
var node = new Uri("http://localhost:49997");
var settings = new ConnectionSettings(
node,
defaultIndex: "my-application"
);
var client = new ElasticClient(settings);
var uporabnik = new uporabnik
{
idUporabnik = 99,
ime = "John",
priimek = "Schwarz"
};
var index = client.Index(uporabnik);
if (!index.IsValid)
{
Log.Error("Error when indexing.");
}
var results = client.Search<uporabnik>(s => s.Query(q => q.Term(p => p.priimek, "Novak")));
return View();
}

I tried Console.WriteLine(index.ServerError.Error), but there comes an error: Object reference not set to an instance of an object. So I do not know, what is error message.
Class uporabnik is below.
public partial class uporabnik
{
public uporabnik()
{
this.ocena = new HashSet<ocena>();
this.predmet = new HashSet<predmet>();
this.studentpredmet = new HashSet<studentpredmet>();
}
[Required]
public int idUporabnik { get; set; }
public Nullable<int> vpisnaStevilka { get; set; }
[Required]
[RegularExpression(#"^[A-z]*$"]
public string ime { get; set; }
[Required]
[RegularExpression(#"^[A-z]*$"]
public string priimek { get; set; }
[RegularExpression(#"^[\w\d-\.]+#([\w\d-]+\.)+[\w-]{2,4}$"]
public string email { get; set; }
public string geslo { get; set; }
[Required]
public string mobi { get; set; }
[Required]
[RegularExpression(#"^[MZ]*$"]
public string spol { get; set; }
[RegularExpression(#"^[123]{1}$"]
public Nullable<int> letnikStudija { get; set; }
public System.DateTime datumRegistracije { get; set; }
public System.DateTime zadnjiDostop { get; set; }
public int idVloge { get; set; }
[JsonIgnore]
public virtual ICollection<ocena> ocena { get; set; }
[JsonIgnore]
public virtual ICollection<predmet> predmet { get; set; }
[JsonIgnore]
public virtual ICollection<studentpredmet> studentpredmet { get; set; }
[JsonIgnore]
public virtual vloga vloga { get; set; }
}

Related

ASP.NET MVC 5 A circular reference was detected while serializing an object of type 'Data.Item'

I am getting a circular reference error in my ASP.NET MVC Project
Here is the Model
public partial class Item
{
public Item()
{
this.Inventories = new HashSet<Inventory>();
this.PurchasesDetails = new HashSet<PurchasesDetail>();
this.SalesDetails = new HashSet<SalesDetail>();
}
public int Id { get; set; }
public string Code { get; set; }
public int CategoryID { get; set; }
public string Name { get; set; }
public int MeasurementID { get; set; }
public int Quantity { get; set; }
public decimal BuyPrice { get; set; }
public decimal SalePrice { get; set; }
public decimal CommisionRate { get; set; }
public Nullable<System.DateTime> MftDate { get; set; }
public Nullable<System.DateTime> ExpDate { get; set; }
public Nullable<int> StockLimit { get; set; }
public string Description { get; set; }
public string UserID { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Inventory> Inventories { get; set; }
public virtual Measurement Measurement { get; set; }
public virtual ICollection<PurchasesDetail> PurchasesDetails { get; set; }
public virtual ICollection<SalesDetail> SalesDetails { get; set; }
}
And Here is code to get the JSON
db.Configuration.ProxyCreationEnabled = false;
var items = db.Items.Include(i => i.AspNetUser).Include(i => i.Category).Include(i => i.Measurement).ToList();
return Json(new { data = items }, JsonRequestBehavior.AllowGet);
I tried with db.Configuration.ProxyCreationEnabled = false; but it's not working. Any help would be highly appreciated.
I faced the same problem and I tried this
var plan_master = from s in db.Plan_Master select s;
var plans = plan_master.Select(S => new
{
S.Plan_ID,
S.Plan
});
return Json(new { data = plans }, JsonRequestBehavior.AllowGet);
In global.asax put this code for global Json serialization settings :
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
Try to change following section of code with below:
string json = JsonConvert.SerializeObject(items, Formatting.None);
return Json(new { data = json }, JsonRequestBehavior.AllowGet);

Unable to add an item to a database, ModelState.IsValid == false

I am working on an ASP.NET MVC application. Basically right now I'am trying to do the following: I created an API helper class that deserializes JSON data returned from Google Books API. In my Create.cshtml I only want to pass the ISBN of the book I am trying to add, however, as I discovered in debugger, ModelState.Is valid is false and therefore the new book does not get created. As far as I can see in the debugger, all the data gets pulled from the API correctly into the dictionary, however for some reason I can't store it my DB.
I know that there is probably a more elegant solution for this, but any kind of advice is more than welcome. Thank you for your time.
Here are the code files that might help:
APIHelper : deserializes JSON data and stores it in a Dictionary.
namespace APIHelper
{
public class IndustryIdentifier
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("identifier")]
public string Identifier { get; set; }
}
public class ReadingModes
{
[JsonProperty("text")]
public bool Text { get; set; }
[JsonProperty("image")]
public bool Image { get; set; }
}
public class ImageLinks
{
[JsonProperty("smallThumbnail")]
public string SmallThumbnail { get; set; }
[JsonProperty("thumbnail")]
public string Thumbnail { get; set; }
}
public class VolumeInfo
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("subtitle")]
public string Subtitle { get; set; }
[JsonProperty("authors")]
public IList<string> Authors { get; set; }
[JsonProperty("publisher")]
public string Publisher { get; set; }
[JsonProperty("publishedDate")]
public string PublishedDate { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("industryIdentifiers")]
public IList<IndustryIdentifier> IndustryIdentifiers { get; set; }
[JsonProperty("readingModes")]
public ReadingModes ReadingModes { get; set; }
[JsonProperty("pageCount")]
public int PageCount { get; set; }
[JsonProperty("printType")]
public string PrintType { get; set; }
[JsonProperty("categories")]
public IList<string> Categories { get; set; }
[JsonProperty("maturityRating")]
public string MaturityRating { get; set; }
[JsonProperty("allowAnonLogging")]
public bool AllowAnonLogging { get; set; }
[JsonProperty("contentVersion")]
public string ContentVersion { get; set; }
[JsonProperty("imageLinks")]
public ImageLinks ImageLinks { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("previewLink")]
public string PreviewLink { get; set; }
[JsonProperty("infoLink")]
public string InfoLink { get; set; }
[JsonProperty("canonicalVolumeLink")]
public string CanonicalVolumeLink { get; set; }
}
public class SaleInfo
{
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("saleability")]
public string Saleability { get; set; }
[JsonProperty("isEbook")]
public bool IsEbook { get; set; }
}
public class Epub
{
[JsonProperty("isAvailable")]
public bool IsAvailable { get; set; }
}
public class Pdf
{
[JsonProperty("isAvailable")]
public bool IsAvailable { get; set; }
}
public class AccessInfo
{
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("viewability")]
public string Viewability { get; set; }
[JsonProperty("embeddable")]
public bool Embeddable { get; set; }
[JsonProperty("publicDomain")]
public bool PublicDomain { get; set; }
[JsonProperty("textToSpeechPermission")]
public string TextToSpeechPermission { get; set; }
[JsonProperty("epub")]
public Epub Epub { get; set; }
[JsonProperty("pdf")]
public Pdf Pdf { get; set; }
[JsonProperty("webReaderLink")]
public string WebReaderLink { get; set; }
[JsonProperty("accessViewStatus")]
public string AccessViewStatus { get; set; }
[JsonProperty("quoteSharingAllowed")]
public bool QuoteSharingAllowed { get; set; }
}
public class SearchInfo
{
[JsonProperty("textSnippet")]
public string TextSnippet { get; set; }
}
public class Item
{
[JsonProperty("kind")]
public string Kind { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("etag")]
public string Etag { get; set; }
[JsonProperty("selfLink")]
public string SelfLink { get; set; }
[JsonProperty("volumeInfo")]
public VolumeInfo VolumeInfo { get; set; }
[JsonProperty("saleInfo")]
public SaleInfo SaleInfo { get; set; }
[JsonProperty("accessInfo")]
public AccessInfo AccessInfo { get; set; }
[JsonProperty("searchInfo")]
public SearchInfo SearchInfo { get; set; }
}
public class RootObject
{
[JsonProperty("kind")]
public string Kind { get; set; }
[JsonProperty("totalItems")]
public int TotalItems { get; set; }
[JsonProperty("items")]
public IList<Item> Items { get; set; }
}
public class APIHelper
{
public string Get(string uri)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
public Dictionary<string, string> DictionaryReturnData(string isbn)
{
string path = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;
string json = Get(path);
Dictionary<string, string> responses = new Dictionary<string, string>();
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
foreach (var obj in rootObject.Items )
{
responses.Add("Title", obj.VolumeInfo.Title);
responses.Add("Description", obj.VolumeInfo.Description);
responses.Add("Image", obj.VolumeInfo.ImageLinks.Thumbnail);
responses.Add("Authors", string.Join(",", obj.VolumeInfo.Authors)); //list of strings
responses.Add("Genre", string.Join(",", obj.VolumeInfo.Categories)); //list of strings
responses.Add("Isbn", isbn);
responses.Add("Publisher", obj.VolumeInfo.Publisher);
responses.Add("PublishedDate", obj.VolumeInfo.PublishedDate);
responses.Add("PageCount", obj.VolumeInfo.PageCount.ToString());
}
return responses;
}
}
}
My Book class:
namespace BookstoreWeb.Models
{
public class Book
{
public int Id { get; set; }
[Required]
public string Isbn { get; set; }
[Required]
public string Title { get; set; }
public string Author { get; set; }
public double Price { get; set; }
[Required]
public string Description { get; set; }
public string Publisher { get; set; }
public string PublishedDate { get; set; }
public string PageCount { get; set; }
public string Thumbnail { get; set; }
public string Genre { get; set; }
}
}
Create Action
[HttpPost]
public IActionResult Create(Book model)
{
APIHelper.APIHelper helper = new APIHelper.APIHelper();
var responses = helper.DictionaryReturnData(model.Isbn);
model.Author = responses["Authors"];
model.Genre = responses["Genre"];
model.Isbn = responses["Isbn"];
model.Price = 10.00;
model.Title = responses["Title"];
model.Description = responses["Description"];
model.Publisher = responses["Publisher"];
model.PublishedDate = responses["PublishedDate"];
model.PageCount = responses["PageCount"];
model.Thumbnail = responses["Image"];
if (ModelState.IsValid) //check for validation
{
var newBook = new Book
{
Author = model.Author,
Genre = model.Genre,
Isbn = model.Isbn,
Price = model.Price,
Title = model.Title,
Description = model.Description,
Publisher = model.Publisher,
PublishedDate = model.PublishedDate,
PageCount = model.PageCount,
Thumbnail = model.Thumbnail,
};
newBook = _bookstoreData.Add(newBook);
_bookstoreData.Commit();
return RedirectToAction("Details", new {id = newBook.Id});
}
Removing the annotations [Required] from Book class seems to have solved the issue.

Save list to database entity framework

I have the following code:
internal static bool SaveUOSChangeLog(List<Contracts.DataContracts.UOSChangeLog> values, string user)
{
try
{
using(var ctx = new StradaDataReviewContext2())
{
values.ForEach(u => { u.Username = user; u.Changed = DateTime.Now; });
var test = ctx.UOSChangeLog.Add(values);
ctx.SaveChanges();
return true;
}
}
The thing I want to do Is to save values to the database. However, I get a the following error message:
Here is my Contracts.DataContracts.UOSChangeLog:
public int? Id { get; set; }
public int Accident_nr { get; set; }
public int Refnr { get; set; }
public int Action { get; set; }
public string Old_data { get; set; }
public string New_data { get; set; }
public DateTime SearchedFromDate { get; set; }
public DateTime SearchedToDate { get; set; }
public DateTime Changed { get; set; }
public string Username { get; set; }
public string Comment { get; set; }
And here Is my Services.StradaDataReview2Model.UOSChangeLog that are used as a DbSet
[Table("UOSChangeLog")]
public partial class UOSChangeLog
{
[Required]
public int? Id { get; set; }
public int Accident_nr { get; set; }
[Required]
public int Refnr { get; set; }
[Required]
public int Action { get; set; }
[Required]
public string Old_data { get; set; }
[Required]
public string New_data { get; set; }
[Required]
public DateTime SearchedFromDate { get; set; }
[Required]
public DateTime SearchedToDate { get; set; }
[Required]
public DateTime Changed { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Comment { get; set; }
}
You're trying to add a list with the Add method which takes a single object, just keep it simple and use a foreach:
using(var ctx = new StradaDataReviewContext2())
{
foreach(var value in values)
{
value.Username = user;
value.Changed = DateTime.Now;
ctx.UOSChangeLog.Add(value);
}
ctx.SaveChanges();
return true;
}
Just use a simple foreach, linq is a querying language, not a modifying language.
Please use addrange method.
db.TheTable.AddRange(TheList)
db.SaveChanges();
You can use Entity Framework's .AddRange method to add a collection of objects to your Db.
MSDN
It will look like:
using(var ctx = new StradaDataReviewContext2())
{
values.ForEach(u => { u.Username = user; u.Changed = DateTime.Now; });
var test = ctx.UOSChangeLog.AddRange(values);
ctx.SaveChanges();
return true;
}

cannot implicitly convert type System.Collections.Generic.List<char>

I am trying to create a list of customer names that is fetched from a Json call but I get an error:
cannot implicitly convert type System.Collections.Generic.List<char>
to System.Collections.Generic.List<string>
I am using these 2 classes:
Customers:
namespace eko_app
{
static class Customers
{
public static List<CustomerResponse> GetCustomers(string customerURL)
{
List<CustomerResponse> customers = new List<CustomerResponse>();
try
{
var w = new WebClient();
var jsonData = string.Empty;
// make the select products call
jsonData = w.DownloadString(customerURL);
if (!string.IsNullOrEmpty(jsonData))
{
// deserialize the json to c# .net
var response = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonData);
if (response != null)
{
customers = response.response;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return customers;
}
public class BusinessAssociate
{
public string business_associate_id { get; set; }
public string created_by { get; set; }
public DateTime created { get; set; }
public DateTime modified { get; set; }
public bool? deleted { get; set; }
public string business_id { get; set; }
public string identity_id { get; set; }
public string associate_type { get; set; }
public string name { get; set; }
}
public class Identity
{
public string identity_id { get; set; }
public string created_by { get; set; }
public DateTime created { get; set; }
public DateTime modified { get; set; }
public bool? deleted { get; set; }
public string name { get; set; }
public object identity_type { get; set; }
}
public class ChartOfAccount
{
public string chart_of_accounts_id { get; set; }
public DateTime created { get; set; }
public DateTime modified { get; set; }
public string created_by { get; set; }
public string deleted { get; set; }
public string account_id { get; set; }
public string account_name { get; set; }
public string business_id { get; set; }
public string account_category { get; set; }
public string accounts_groups_id { get; set; }
public string cash_equivalent { get; set; }
public string acc_category { get; set; }
public decimal? balance { get; set; }
public decimal? credit_balance { get; set; }
public decimal? debit_balance { get; set; }
public decimal? absolute_balance { get; set; }
public string balance_type { get; set; }
public decimal? raw_balance { get; set; }
public string extended_name { get; set; }
public string normal_balance_type { get; set; }
}
public class CustomerResponse
{
public BusinessAssociate BusinessAssociate { get; set; }
public Identity Identity { get; set; }
public ChartOfAccount ChartOfAccount { get; set; }
}
public class Messages
{
public string msgs { get; set; }
public string errs { get; set; }
}
public class RootObject
{
public List<CustomerResponse> response { get; set; }
public Messages messages { get; set; }
}
}
}
HomeForm:
private void GetCustomerNameList()
{
// get customers
customerURL = "https://eko-app.com/BusinessAssociate/list_associates/1/sessionId:" + sessionID + ".json";
var customers = Customers.GetCustomers(customerURL);
List<string> customerNames = new List<string>();
foreach (var c in customers)
{
customerNames = c.BusinessAssociate.name.ToList(); <--------error thrown here
}
}
The error is thrown at customerNames = c.BusinessAssociate.name.ToList(); on the HomeForm.
What am I doing wrong in creating a list of customer names?
I think you wanted to add all Customer.BusinessAssociate names to list:
foreach (var c in customers)
{
customerNames.Add(c.BusinessAssociate.name);
}
What you originally written converted each name string to char list.
You're assigning a list of chars (string) into a list of strings.
Try something like this outside of the foreach loop:
customerNames = customers.Select(x => x.BusinessAssociate.name).ToList();
This also makes the initialization of cutomerNames redundant.
Instead of foreach use:
customerNames = customers.Select(c => c.BusinessAssociate.name).ToList();

Populating a viewmodel from a database model but getting object reference error

I had a similar problem with a dictionary - now I'm trying to populate a viewmodel, to return a JSON object to a GET request.
My viewmodel is:
public class HotelInventoryta
{
public int api_version { get; set; }
public string lang { get; set; }
public List<Hotel_List_ta> hotels { get; set; }
}
public class Hotel_List_ta
{
public int ta_id { get; set; }
public string partner_id { get; set; }
public string name { get; set; }
public string street { get; set; }
public string city { get; set; }
public string postal_code { get; set; }
public string state { get; set; }
public string country { get; set; }
public double latitude { get; set; }
public double longitude { get; set; }
public string desc { get; set; }
public string url { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string fax { get; set; }
}
My DataBase model is:
[Table("tblHotel")]
public class Hotelta
{
[Key()]
[Column("hotel_id")]
public long hotel_id { get; set; }
public string hotel_name { get; set; }
public string hotel_add1 { get; set; }
public string hotel_towncity { get; set; }
public string hotel_pc { get; set; }
public string hotel_country { get; set; }
public string hotel_pass { get; set; }
public string hotel_email { get; set; }
public string hotel_tel { get; set; }
public string hotel_fax { get; set; }
}
My controller code to populate the viewmodel is:
private HoteltaContext dbh = new HoteltaContext();
//
// GET: /ta/hotel_inventory
[HttpGet]
public HotelInventoryta hotel_inventory(int api_version, string lang)
{
{
HotelInventoryta hotelinventory = new HotelInventoryta();
hotelinventory.api_version = api_version;
hotelinventory.lang = lang;
// Get data from database
var h = dbh.Hotelta.Where(x => x.hotel_id != 0).ToList();
// loop through each result, and add it to the hotelinventory.hotels model
foreach (var ht in h)
{
// I get the exception on the next line
hotelinventory.hotels.Add(new Hotel_List_ta
{
ta_id = 0,
partner_id = ht.hotel_id.ToString(),
name = ht.hotel_name,
street = ht.hotel_add1,
city = ht.hotel_towncity,
postal_code = ht.hotel_pc,
country = ht.hotel_country,
url = "http://www.me.com",
email = ht.hotel_email,
phone = ht.hotel_tel,
fax = ht.hotel_fax
});
}
return hotelinventory;
}
}
The error is:
Object reference not set to an instance of an object
Firstly, can you help me resolve the error - and if possible, confirm if the way I am reading from the database and populating the viewmodel, is the best way to do it?
Thank you, Mark
This is because the hotels property is never initialized. You could do this in the constructor of HotelInventoryta:
public class HotelInventoryta
{
public HotelInventoryta()
{
hotels = new List<Hotel_List_ta>();
}
// ...
}
Now you initialzed the property with an empty collection, so you can add items to it, rather than hotels being null which causes your exception.

Categories