RavenDB load related data not working - c#

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;
}
}

Related

Saving Binary Data FHIR DB

I am trying to save Binary data to FHIR DB.
This is my method:
public static Patient SavePdfForms(string resource, HttpClientEventHandler messageHandler, string[] pdfForms, Patient patient, FhirClient BinaryBundleClient)
{
Bundle BinaryBundle = new Bundle();
BinaryBundle.Type = Bundle.BundleType.Collection;
try
{
foreach (var item in pdfForms)
{
Binary BinaryData = new Binary();
var bytearray = Encoding.ASCII.GetBytes(item);
BinaryData.Data = bytearray;
BinaryData.ContentType = "application/fhir+json";
var binaryResource = BinaryBundleClient.Create(BinaryData);
BinaryBundle.AddResourceEntry(BinaryData, resource + "/BundleResource/" + binaryResource.Id);
}
}
catch (Exception ex)
{
throw;
}
var bundleId = BinaryBundleClient.Create(BinaryBundle);
patient.Identifier.Add(new Identifier("BinaryBundle", bundleId.Id));
return BinaryBundleClient.Update(patient);
}
The string[] of pdfForms is base64 and for each form I am creating a new binary and adding data and content type. But the line var binaryResource = BinaryBundleClient.Create(BinaryData); throws an error and data is not a valid json. I tried with different content type but that is not working. Any ideas why?
Assuming you are creating a new resource instance in BinaryBundleClient.Create(BinaryData) and the server to store it.
In your case, you directly pass the binary information in Fhirclient.Create(your data)
binaryResource = BinaryBundleClient.Create(BinaryData);
You must mention the type of the resource instance which follows:
Create Fhir client
var client = new FhirClient("http://server.fire.ly");
After Creating FhirClient You have to create a new resource instance. It will be like
var pat = new Patient() { /* set up data */ };
var created_pat = client.Create<Patient>(pat);
this interaction will throw an Exception when things go wrong, in most cases a FhirOperationException. This exception has an Outcome property that contains an OperationOutcome resource, and which you may inspect to find out more information about why the interaction failed. Most FHIR servers will return a human-readable error description in the OperationOutcome to help you out.
Refer here

C# dynamics throws RuntimeBinderException when accessing property

I'm getting a RuntimeBinderException when attempting to read a property from a dynamic object. This is no doubt one of those issues where I've not got the syntax quite right, but I'm just not seeing it....
Using a simple LinqPad script, the following works fine:
void Main()
{
var response = new
{
DotNet = Environment.Version,
ServerName = Environment.MachineName,
};
dynamic d = response;
var x = d.DotNet as Version;
x.Major.Dump();
}
If I return it from a Web Method, then I'm running into issues. Here is my simple web method (.Net 5 WebAPI)
public IActionResult GetEnvironmentDetails()
{
var response = new
{
DotNet = Environment.Version,
ServerName = Environment.MachineName,
};
return this.Ok(response);
}
In my unit test, I can read the property using reflection, but not using dynamics:
var c = new MyController();
var response = c.GetEnvironmentDetails() as OkObjectResult;
// This next line gets me the property using reflection:
Version dotNet = response.Value.GetType().GetProperty("DotNet").GetValue(response.Value, null) as Version;
// But...using dynamics
dynamic d = response.Value;
// then the following fails for me
object x = d.DotNet;
If I put the variable d in my WATCH window, then the Value shows as { DotNet = {5.0.4}, ServerName = "MyComputerName" } and the Type is <Anonymous Type>.

ASP.NET Core 2 Windows Authentication/AD Get Groupmembers

Like the title says, i need to get the members of a group from my Active directory.
Code:
using(var p_con = new PrincipalContext(ContextType.Machine))
{
var grps = GroupPrincipal.FindByIdentity(p_con, IdentityType.Sid, "S-1-5-21-205523278-2745993604-4001200492-1027");
var users = grps.GetMembers();
}
But my code throws the follwing error in the Membersproperty of the 'grps' var.
Members = 'grps.Members' threw an exception of type
'System.TypeLoadException'
If i try it the other way, searching for the groups of a member, i get the same error.
using (var p_con = new PrincipalContext(ContextType.Machine))
{
var up = new UserPrincipal(p_con);
using (var search = new PrincipalSearcher(up))
{
foreach (var user in search.FindAll())
{
var _grp = user.GetGroups();
}
}
}
The group/user it self is correctly loaded except the Users\Groups.
Am i missing something in the setup?
I am using ASP.NET Core 2 and the current Windows.Compatibility Pack (which includes the current verion of the DirectoryServices).
The authentication runs via Http.sys

How to get list of all collections in RavenDB 4

There was this approach in previous versions -
var terms = new GetTermsOperation("Raven/DocumentsByEntityName", "Tag", "", 1024);
But now it doesn't work. I tried to use another command:
var op = new GetCollectionStatisticsOperation();
var collectionStats = store.Maintenance.Send(op);
But it throws an error - System.ArgumentNullException: 'Value cannot be null.
Parameter name: key'
Then i found out how to get the all collections from the browser admin panel:
from #all_docs select distinct #metadata.#collection
How to translate that snippet to c# code?
If you don't have a database assigned at the document store level, you need to specify it explicitly, like so:
var collectionStats = store.Maintenance.ForDatabase("db-name").Send(op);
I found a clue - my DocumentStore variable didn't had an assigned Database ( it was assigned in OpenSession constructor):
//Wrong variant
IDocumentStore store = new DocumentStore()
{
Urls = new string[] { Host }, /*Database = "testdb"*/
}
using (IDocumentSession session = store.OpenSession(dbName))
{
//some code
}
//Good variant
IDocumentStore store = new DocumentStore()
{
Urls = new string[] { Host }, Database = "testdb"
}
using (IDocumentSession session = store.OpenSession())
{
//some code
}

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

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

Categories

Resources