Elasticsearch while doing update operation , to select that particular index getting exception - c#

In am new in elasticsearch and i am trying to do update operation with elasticsearch but for that when am trying to filter and select that particular code i am getting execption and the exception is:
An exception of type 'ElasticsearchCRUD.ElasticsearchCrudException' occurred in ElasticsearchCRUD.dll but was not handled in user code,
Additional information: ElasticSearchContextGet: HttpStatusCode.BadRequestNo handler found for uri [//skillwithlistofdetailss/skillwithlistofdetails/1] and method [GET]
and my method is below:
public void UpdateSkill(long updateId, string updateName, string updateDescription, List<SkillDetail> updateSkillDetailsList)
{
using (var context = new ElasticsearchContext(ConnectionString, _elasticSearchMappingResolver))
{
//var addressItem = _elasticsearchContext.SearchById<SkillWithListOfDetails>(updateId);
//var entityAddress = _entityFrameworkContext.Address.First(t => t.Id == addressItem.Id);
try
{
var skill = context.GetDocument<SkillWithListOfDetails>(updateId);
skill.Updated = DateTime.UtcNow;
skill.Name = updateName;
skill.Description = updateDescription;
skill.SkillDetails = updateSkillDetailsList;
foreach (var item in skill.SkillDetails)
{
item.Updated = DateTime.UtcNow;
}
context.AddUpdateDocument(skill, skill.Id);
context.SaveChanges();
}
catch(Exception e)
{
throw e;
}
}
}
and i am getting exception in this line of code:--
var skill = context.GetDocument(updateId);

There seems to be a problem with index/type name somewhere? The error message says: "ElasticSearchContextGet: HttpStatusCode.BadRequestNo handler found for uri [//skillwithlistofdetailss/skillwithlistofdetails/1] and method [GET]:".
Check your index and type are correct or not.
Index: skillwithlistofdetailss
Type: skillwithlistofdetails

Related

EntityFramework error when trigger SaveChangesAsync()

Got an error stated
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
when I trigger SaveChangesAsync() function. See my code below:
using (var context = new CommonDBContext()) {
var bbrs = await context.Table1
.ToListAsync();
var lastIndexToRemove = pimc.Result.IndexOf("UIX/");
if (lastIndexToRemove > -1)
{
bbrPimcStr = pimc.Result.Remove(0, lastIndexToRemove);
}
foreach (var bbr in bbrs) {
bbr.XBBR = xbbrStr;
bbr.LastUpdated = DateTime.Now;
bbr.LastUpdatedBy = userId;
if (!pimc.HasError)
{
var graveDKI = context.graveDKIStore
.Where(x => x.RefId == bbr.Id)
.FirstOrDefault();
if (graveDKI != null)
graveDKI.GraveDKI = bbrPimcStr ;
else
context.graveDKIStore.Add(new graveDKIStore
{
Id = Guid.NewGuid(),
GraveDKI = bbrPimcStr ,
RefId = bbr.Id,
MsgType = "PPIXFFT"
});
}
}
return await context.SaveChangesAsync(); // Got issue here
Can someone tell me whats wrong with my code? thanks.
Update: Added exception stack.
I fixed the issue by checking the length of the character, it might be different errors base on what data annotation or validator annotation that you placed on your object. To double check if your validations are correct, you can check through exception stack under EntityValidationErrors to get more in-depth information about it, see image below.
public class GraveDKIStore {
...
[MaxLength(5)] // The issue is here so I changed it to 10.
public string MsgType { get; set; }
...
}
P.S. thanks to Roman Doskoch for a very helpful advice.

RavenDB load related data not working

The following code throws an exception on the session.Load<Employee>(order.Employee), but I have no problem querying an employee directly.
static void LoadRelatedData()
{
using (var session = mystore.OpenSession())
{
var employeeFromQuery = session.Query<Employee>().FirstOrDefault(); //works
var order = session.Include<Order>(o => o.Employee).Load("orders/819"); //works
var employeeRelatedToOrder = session.Load<Employee>(order.Employee); //EXCEPTION
var dynamicRelatedToOrder = session.Load<dynamic>(order.Employee); //works
}
}
private static IDocumentStore mystore = new DocumentStore()
{
Url = "http://localhost:4444/RavenDB",
DefaultDatabase = "Hello"
}.Initialize();
The exception I get is -
An unhandled exception of type 'System.InvalidCastException' occurred in Raven.Client.Lightweight.dll
Additional information: Unable to cast object of type 'Raven.Abstractions.Linq.DynamicJsonObject' to type 'RavenApp.Employee'
.
I'm basing my code on http://ravendb.net/docs/article-page/2.5/Csharp/client-api/querying/handling-document-relationships
The employee and order data are generated by the Raven Create Sample Data task.
As you've used Include, the order.Employee should be populated for you and not require a second load.
static void LoadRelatedData()
{
using (var session = mystore.OpenSession())
{
var employeeFromQuery = session.Query<Employee>().FirstOrDefault();
var order = session.Include<Order>(o => o.Employee).Load("orders/819");
// Access them directly, as they have been resolved
var employeeRelatedToOrder = order.Employee;
var dynamicRelatedToOrder = (dynamic)order.Employee;
}
}

An exception of type 'System.ArgumentException' occurred in cms.dll but was not handled in user code

Trying to go to a page on my site, got a blank screen and decided to try again with Visual Studio 2012 loaded and debugging it, now I get this error when the page loads:
An exception of type 'System.ArgumentException' occurred in cms.dll but was not handled in user code and points to the following code in HeaderControl.ascx.cs:
else if(new umbraco.cms.businesslogic.template.Template((Context.GetContent()).template).Alias == "TemplateLanguage")
This code is inside the following method:
public void LoadData()
{
_Location = HttpContext.Current.GetLocation();
if (Context.GetContent().NodeTypeAlias == "Home")
{
TheHomeHeaderPH.Visible = true;
ThePhonePH.Visible = true;
_MenuStyle = "var-nav nav-large";
LoadMenuTopControl();
LoadMenuMainControl();
}
else if(new umbraco.cms.businesslogic.template.Template((Context.GetContent()).template).Alias == "TemplateLanguage")
{
TheContentHeaderPH.Visible = true;
_MenuStyle = "nav-small";
LoadContentMenuTopControl();
LoadMenuLanguageControl();
}
else
{
MMG.BusinessLayer.Content theContent = MMG.BusinessLayer.Content.GetCached(Context.GetContent());
if (theContent.TemplateColor == "168C9C")
{
TheHomeHeaderPH.Visible = true;
_MenuStyle = "nav-small";
LoadMenuTopControl();
LoadMenuMainControl();
}
else
{
TheContentHeaderPH.Visible = true;
LoadContentMenuTopControl();
LoadContentMenuMainControl();
}
}
}
How can I fix this problem? System.ArgumentException says this: {"No node exists with id '0'"}
I would guess it's the (Context.GetContent()).template that breaks somehow and I assume GetContent is a custom extension method.
The exception {"No node exists with id '0'"} usually means that you couldn't fetch the node you requested.
Instead try
else if(new umbraco.cms.businesslogic.template.Template(umbraco.uQuery.GetCurrentNode().template).Alias == "TemplateLanguage")
If that doesn't work it means you are running the code in a context where the CurrentNode is unavailable. In that case you must extend your LoadData method with a nodeId parameter.

EF Change Tracker: Collection was modified; enumeration operation may not execute

I'm getting an error when I loop through a collection. I'm not changing the list at any point, but it gives me the following "Collection was modified; enumeration operation may not execute. Following code shows the method that I have this Parallel.Foreach.
public void DownloadImages()
{
IList<Vehicle> vehicles = _repository.Retrieve().ToList();
Parallel.ForEach(vehicles, vehicle =>
{
IList<VehiclePhoto> vehiclePhotos =
vehicle.VehiclePhotos.Where(x => x.ImageStatus == ImageStatus.Inactive).ToList();
if (vehiclePhotos.Count > 0)
{
Parallel.ForEach(vehiclePhotos, photo =>
{
using (var client = new WebClient())
{
try
{
string fileName = Guid.NewGuid() + ".png";
string filePath = _imagePath + "\\" + fileName;
client.DownloadFile(photo.ImageUrl, filePath);
photo.FileName = fileName;
photo.ImageStatus = ImageStatus.Active;
}
catch (Exception)
{
}
}
});
_repository.Save(vehicle);
}
});
}
This happens when _repository.Save(vehicle) is called. Following code will show the save changes method. base.SaveChanges(); is the place where error get raised.
public override int SaveChanges()
{
DateTime nowAuditDate = DateTime.Now;
IEnumerable<System.Data.Entity.Infrastructure.DbEntityEntry<DomainEntity>> changeSet = ChangeTracker.Entries<DomainEntity>();
if (changeSet != null)
{
foreach (System.Data.Entity.Infrastructure.DbEntityEntry<DomainEntity> entry in changeSet)
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.Created = nowAuditDate;
entry.Entity.Modified = nowAuditDate;
break;
case EntityState.Modified:
entry.Entity.Modified = nowAuditDate;
break;
}
}
}
return base.SaveChanges();
}
Any ideas on this?
EDITED:
I was trying to fix this above mentioned error and changed few code lines in DownloadImages method. Those changes are as follows:
Instead of
IList<Vehicle> vehicles = _repository.Retrieve().ToList();
I used var
var vehicles = _repository.Retrieve().AsParallel();
Instead of
IList<VehiclePhoto> vehiclePhotos =
vehicle.VehiclePhotos.Where(x => x.ImageStatus == ImageStatus.Inactive).ToList();
I used var
var vehiclePhotos =
vehicle.VehiclePhotos.Where(x => x.ImageStatus == ImageStatus.Inactive).AsParallel();
When I tried to run the code again. It gave me a different error: Error is as follows:
In the header it says
System.Data.Entity.Infrastructure.DbUpdateException
But in the innerException
System.Data.Entity.Core.UpdateException
ExecuteNonQuery requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized.
This happens because you are iterating over vehicles and the code inside the loop is changing the elements of the enumeration vehicles. Also, looping through vehiclePhotos and changing the elements of it.
I usually solve this by using an explicit for loop, i.e.:
for(var i = 0; i < vehicles.Count; i++)
{
var vehicle = vehicles.ElementAt(i);
// process vehicle
}
However, if you need to use Parallel.ForEach, you could try creating an array of integers with length of vehicles.Count, iterate over that and use it as index for vehicles.

SPListItem Save conflict while Update

(1) var list1 = web.GetList("/lists/list1");
(2) var item1 = list1.GetItemById(10001);
(3) ...
take breakpoint here, open item with ID = 10001 for edit, change 'Title' fields and save it. Then run code follow:
(4)item1[SPBuiltInFieldId.Title] = "some text";
(5)item1.Update();
row (5) throws save conflict exception.
How can to lock item for edit at line (3)? Or any other approach to avoid conflict?
You have to check the SPListItem manually
try
{
var item = list.GetItemById(3);
item["MyField"] = "FooBar";
item.Update();
}
catch(SPException conflictEx)
{
// handle conflict by re-evaluating SPListItem
var item = list.GetItemById(3);
// ..
}
I don't know any other mechanism atm.
// *create a new SPWeb object for each list modification otherwise
we'll get Save Conflict*
from the following URL
http://platinumdogs.me/2010/01/21/sharepoint-calling-splist-update-causes-save-conflict-spexception/
exceptions
using (var thisWeb = featSite.OpenWeb(featWeb.ID))
{
try
{
var listUpdate = false;
var theList = thisWeb.Lists[att.Value];
// change list configuration
// .....
// commit List modifications
if (listUpate)
theList.Update();
}
catch
{
// log the event and rethrow
throw;
}
}
}
}
Another approach is using Linq to SharePoint, Linq to SharePoint offers you a conflict resolution mechanism
SharePoint's LINQ provider is querying for concurrent changes when you try to save changes you've made using the SubmitChanges method.
When a conflict has been found, a ChangeConflictException will be thrown.
foreach(var notebook in spSite.Notebooks)
{
notebook.IsTopNotebook = true;
}
try
{
spSite.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch(ChangeConflictException ex)
{
foreach(ObjectChangeConflict occ in spSite.ChangeConflicts)
{
if (((Notebook)occ.Object).Memory > 16)
{
foreach (MemberChangeConflict field in occ.MemberConflicts)
{
if (field.Member.Name == "IsTopNotebook")
{
field.Resolve(RefreshMode.KeepCurrentValues);
}
else
{
field.Resolve(RefreshMode.OverwriteCurrentValues);
}
}
}
else
{
occ.Resolve(RefreshMode.KeepCurrentValues);
}
}
spSite.SubmitChanges();
}

Categories

Resources