How to get an element in FHIR API? - c#

I tried to get the element like Identifier, Location, Period, ... But not working. How can I get it?
My code follow:
static void Main(string[] args)
{
//The fhir server end point address
string ServiceRootUrl = "http://stu3.test.pyrohealth.net/fhir";
//Create a client to send to the server at a given endpoint.
var FhirClient = new Hl7.Fhir.Rest.FhirClient(ServiceRootUrl);
// increase timeouts since the server might be powered down
FhirClient.Timeout = (60 * 1000);
Console.WriteLine("Press any key to send to server: " + ServiceRootUrl);
Console.WriteLine();
Console.ReadKey();
try
{
//Attempt to send the resource to the server endpoint
Hl7.Fhir.Model.Bundle ReturnedSearchBundle = FhirClient.Search<Hl7.Fhir.Model.Patient>(new string[] { "status=planned" });
Console.WriteLine(string.Format("Found: {0} Fhirman patients.", ReturnedSearchBundle.Total.ToString()));
Console.WriteLine("Their logical IDs are:");
foreach (var Entry in ReturnedSearchBundle.Entry)
{
Console.WriteLine("ID: " + Entry.Resource.Id);
Console.WriteLine("ID2: " + Entry.Identifier);
}
Console.WriteLine();
}
catch (Hl7.Fhir.Rest.FhirOperationException FhirOpExec)
{
//Process any Fhir Errors returned as OperationOutcome resource
Console.WriteLine();
Console.WriteLine("An error message: " + FhirOpExec.Message);
Console.WriteLine();
string xml = Hl7.Fhir.Serialization.FhirSerializer.SerializeResourceToXml(FhirOpExec.Outcome);
XDocument xDoc = XDocument.Parse(xml);
Console.WriteLine(xDoc.ToString());
}
catch (Exception GeneralException)
{
Console.WriteLine();
Console.WriteLine("An error message: " + GeneralException.Message);
Console.WriteLine();
}
Console.WriteLine("Press any key to end.");
Console.ReadKey();
}
The result is System.Collections.Generic.List`1[Hl7.Fhir.Model.Identifier]

Your search is for a Patient, which does not have a 'status' search parameter nor field. The server you use eliminates the parameter for the search, and sends back a Bundle with Patients in the entries - this is according to the FHIR specification.
The first line in your foreach (Console.WriteLine("ID: " + Entry.Resource.Id);) will output the technical id of the resource. Since there is no Identifier field on the Entry, I assume your second one actually reads Entry.Resource.Identifier.
The Patient.identifier field is a 0..* list of Identifiers, so you would have to take one of them. The Identifier datatype in turn is a complex datatype, with usually a system and value field filled in. So, you could do something like this - assuming the Identifier list contains an item:
var patient = (Patient)Entry.Resource;
Console.WriteLine($"Patient identifier: {patient.Identifier[0].System} {patient.Identifier[0].Value}");

Related

Copying a string into a list isn't working - C#, Unity3D

I have a dialogue system and a journal system that should allow the player to copy dialogue lines that have just been said into their journal, however, copying the strings into the list isn't working.
I've been using string.Copy to copy the value of the string instead of the reference, but it doesn't copy anything over at all. Cutting string.Copy and copying the reference doesn't appear to work either. The line I'm copying from does have a value, I printed a debug.log to print the value for it before printing the value of the list items (see below)(edited to include full script).
public class JournalTester : MonoBehaviour
{
public List<DiaEntryClass> diaJournal = new List<DiaEntryClass>();
GameObject diaSysObject;
private DialogueSystem diaSysScript;
string testLine = "inital value for testline";
string testName = "Initial NPC name value";
private void Update()
{
if (Input.GetKey("k"))
{
Debug.Log("K");
diaSysObject = GameObject.Find("DialogueSystem");
diaSysScript = diaSysObject.GetComponent<DialogueSystem>();
testLine = diaSysScript.justSaid;
testName = diaSysScript.justSpoke;
Debug.Log("testLine post copy: " + testLine);
diaJournal.Add(new DiaEntryClass(string.Copy(testLine), "Bernard's Apartment", string.Copy(testName)));
Debug.Log("Using the string.Copy method.....................................................");
Debug.Log("Dialogue Journal, Entry 0, Line: " + diaJournal[0].line);
Debug.Log("Dialogue Journal, Entry 0, Character: " + diaJournal[0].character);
Debug.Log("Dialogue Journal, Entry 0, Location: " + diaJournal[0].location);
diaJournal.Add(new DiaEntryClass(testLine, "Bernard's Apartment", testName));
Debug.Log("Not using the string.Copy method..................................................");
Debug.Log("Dialogue Journal, Entry 1, Line: " + diaJournal[1].line);
Debug.Log("Dialogue Journal, Entry 1, Character: " + diaJournal[1].character);
Debug.Log("Dialogue Journal, Entry 1, Location: " + diaJournal[1].location);
}
}
}
public class DiaEntryClass
{
public string line;
public string location;
public string character;
public DiaEntryClass (string line, string location, string character)
{
line = "initial line";
location = "initial location";
character = "character";
}
}
Above is the custom class I'm using for dialogue entries.
But no matter what I do, it doesn't seem to work like that. Below is my Debug.Log lines:
testLine post copy: Hello! My name is John Doe Using the string.Copy
method..................................................... Dialogue
Journal, Entry 0, Line: Dialogue Journal, Entry 0, Character:
Dialogue Journal, Entry 0, Location: Not using the string.Copy
method.................................................. Dialogue
Journal, Entry 1, Line: Dialogue Journal, Entry 1, Character Dialogue
Journal, Entry 1, Location:
The Character string should print as "John".
The Line string should print as "Hello! My name is John Doe."
The Location string should print as "Bernard's Apartment".
So testLine does have the correct value, since it did successfully print the test line I was using, but that value isn't transferring over into the list and I don't know why. I couldn't find anything about String.Copy in the Unity Documentation, so I was worried I was using something wrong? I don't know for sure.
I made a few updates to your script I hope you can look at these changes and try using them to figure out the issue going on with your script, btw both of the copy and non-copy methods work for me:
Changes to your DiaEntryClass
[System.Serializable] // Makes it so you can view this classes data members in the inspector, so you should see your public list now.
public class DiaEntryClass
{
public string line;
public string location;
public string character;
public DiaEntryClass(string inLine, string inLocation, string inCharacter)
{
// Actually setting my variables to the values passed in...
line = inLine;
location = inLocation;
character = inCharacter;
}
}
Changes to your update
// Update is called once per frame
void Update()
{
// Using GetKeyDown so it runs only once, GetKey runs for every frame the key is held
if (Input.GetKeyDown("k"))
{
Debug.Log("K");
diaSysObject = GameObject.Find("DialogueSystem");
diaSysScript = diaSysObject.GetComponent<DialogueSystem>();
testLine = diaSysScript.justSaid;
testName = diaSysScript.justSpoke;
Debug.Log("testLine post copy: " + testLine);
diaJournal.Add(new DiaEntryClass(string.Copy(testLine), "Bernard's Apartment + copy Method", string.Copy(testName)));
diaJournal.Add(new DiaEntryClass(testLine, "Bernard's Apartment + non-copy method", testName));
int index = 0;
// Foreach to just loop through every entry
foreach (DiaEntryClass dec in diaJournal)
{
Debug.Log("Dialogue Journal, Entry " + index + ", Line: " + dec.line);
Debug.Log("Dialogue Journal, Entry " + index + ", Character: " + dec.character);
Debug.Log("Dialogue Journal, Entry " + index + ", Location: " + dec.location);
index++;
}
}
}

How would I detect and display an HTTP error message(404) on Xamarin if I'm using an API wrapper?

I am currently using Xamarin to create a multiplatform application for the phone. The app idea is basically a Pokemon encyclopedia that utilizes the PokeAPi (https://pokeapi.co/) and also uses the following wrapper library (https://gitlab.com/PoroCYon/PokeApi.NET). Currently, I want it to where if the user types in an incorrect Pokemon into the search bar, it will return an alert error to the user. However, every time I test it and enter in an invalid pokemon, the application stops and Visual Studio/Xamarin informs me of a HTTP404 error. How would I go about this?
I've tried using comparison statements in where if the API call doesn't find the pokemon name, it should pop up with an alert, but VS/Xamarin will stop running the application and display a Http404 exception. I really dont know where to go at this point.
'''
async Task PullData()
{
LoadingIcon.IsRunning = true;
string newPokemon = PokemonFind.Text;
Pokemon p = await DataFetcher.GetNamedApiObject<Pokemon>(newPokemon);
string PokemonName = p.Name;
int PokemonHeight = p.Height;
int PokemonWeight = p.Mass;
int PokemonXp = p.BaseExperience;
int PokemonOrder = p.Order;
OrderLabel.Text = "#" + PokemonOrder;
NameLabel.Text = "Name: " + PokemonName;
HeightWeightLabel.Text = "Height/Weight: " + PokemonHeight.ToString() +" dm " + "/" + PokemonWeight.ToString() + " hg";
ExpLabel.Text = "Experience on defeat: " + PokemonXp.ToString() + "XP";
LoadingIcon.IsRunning = false;
}
'''
I expected it to display an alert message instead of VS/Xamarin stopping the program and throwing me an HTTP404 exception.
Wrap your call inside a try/catch block
try
{
async Task PullData()
}
catch(HttpRequestException ex)
{
//Shows an alert error to the user
}

Google Drive API (v3) --- Download file as a service

hope this question makes sense: Is there a way I can download files from a drive without reiterating the service account every time? So for example, I have a program that allows me to backup my Gapps organization drives. The program currently works like this:
Logs in to each account with the service I created in the Google developer console
Checks the token as a source for changed files from the last time the backup ran to the current execution
IF the token is different, executes a file list request and records the fileId and actual fileName for the files changed, then puts both values into a temporary text document as 2 columns ("fileId,fileName"). Here is what I'm using for the file resource list
Console.WriteLine("Changes detected. Making notes while we go through these.");
if (File.Exists(savelocation + ".deltalog.tok"))
File.Delete(savelocation + ".deltalog.tok");
using (StreamWriter deltalog = new StreamWriter(savelocation + ".deltalog.tok", true))
{
while (pageToken != null)
{
counter1++;
var request = CreateService.BuildService(user).Changes.List(pageToken);
//StreamWriter deltalog = new StreamWriter(savelocation + ".deltalog.tok", true);
request.Fields = "*";
request.Spaces = "drive";
var changes = request.Execute();
foreach (var change in changes.Changes)
{
try
{
string updatedfile = change.File.Name;
//string updatedfile = CreateService.BuildService(user).Files.Get(change.FileId).Execute().Name;
// Record the changed file
Console.WriteLine(user + ": New or changed file found: " + updatedfile + "\n");
logFile.WriteLine(user + ": New or changed file found: " + change.FileId + " --- " + updatedfile);
deltalog.Write(change.FileId + "," + updatedfile+"\n");
deltalog.Flush();
}
Start exporting the files out as documents to my server for backup. To do this, I log into the Gapps domain with my service account 3 different times for one file for each user. Right now, I'm reading the file created from step 3 and splitting the values so that I have the fileId and Filename on hand. The code looks like this:
FilesResource.ListRequest listRequest = CreateService.BuildService(user).Files.List();
listRequest.PageSize = 1000;
listRequest.Fields = "nextPageToken, files(id, name)";
string[] deltafiles = File.ReadAllLines(savelocation + ".deltalog.tok");
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
Console.WriteLine("\nFiles to backup:\n");
if (deltafiles == null)
{
return;
}
else
{
foreach (var file in deltafiles)
{
try
{
// Our file is a CSV. Column 1 = file ID, Column 2 = File name
var values = file.Split(',');
string fileId = values[0];
string fileName = values[1];
fileName = fileName.Replace('\\', '_').Replace('/', '_').Replace(':', '_').Replace('!', '_').Replace('\'', '_').Replace('*', '_');
Console.WriteLine("Filename: " + values[1]);
logFile.WriteLine("ID: " + values[0] + " - Filename: " + values[1]);
var requestfileid = CreateService.BuildService(user).Files.Get(fileId);
var getfile = CreateService.BuildService(user).Files.Get(fileId).Execute();
var request = CreateService.BuildService(user).Files.Export(fileId, getfile.MimeType);
and so forth.
If I try to change the requestfileid to values[0] (which would be the fileId for that file in the loop), then the MediaDownloader doesn't work because it's no longer part of the Files.Get constructor.
Is there anything I can do, or overlooking, so that the service account only has to log in once to do everything it needs per account?
Hope that gibberish makes sense.
I've been using https://developers.google.com/drive/v3/web/quickstart/dotnet and the API documentation as my source for information, and I got everything working the way I want it to, Except for having to log in as the service multiple times for One file. Any help or point in the right direction would sure be appreciated. Thank you!

custom exception handling database insert

I hope you understand me
I have 2 questions
1 How do I implement custom exception handling ?
2 I have my this table
ID
ExceptionName
ClassName
MethodName
FieldName
ErrorMessage
I want to record following for a exception to the table :
what was the error page?
what was the error classname?
what was the error method and What was the name of the fieldname ? How can I get Exception details?
Get Class Name and Method Name Where Exception Occurred From Exception Details
MSSQL + C# mvc framework 4.0
thank you
this is the function which you have to call inside your catch block,
public static void LogException(Exception exc, string source)
{
// Include enterprise logic for logging exceptions
// Get the absolute path to the log file
string logFile = "App_Data/ErrorLog.txt";
logFile = HttpContext.Current.Server.MapPath(logFile);
// Open the log file for append and write the log
StreamWriter sw = new StreamWriter(logFile, true);
sw.WriteLine("********** {0} **********", DateTime.Now);
if (exc.InnerException != null)
{
sw.Write("Inner Exception Type: ");
sw.WriteLine(exc.InnerException.GetType().ToString());
sw.Write("Inner Exception: ");
sw.WriteLine(exc.InnerException.Message);
sw.Write("Inner Source: ");
sw.WriteLine(exc.InnerException.Source);
if (exc.InnerException.StackTrace != null)
{
sw.WriteLine("Inner Stack Trace: ");
sw.WriteLine(exc.InnerException.StackTrace);
}
}
sw.Write("Exception Type: ");
sw.WriteLine(exc.GetType().ToString());
sw.WriteLine("Exception: " + exc.Message);
sw.WriteLine("Source: " + source);
sw.WriteLine("Stack Trace: ");
if (exc.StackTrace != null)
{
sw.WriteLine(exc.StackTrace);
sw.WriteLine();
}
sw.Close();
}
refer to the link:http://msdn.microsoft.com/en-us/library/bb397417(v=vs.140).aspx

Query Active Directory in C#

I am trying to perform a query to Active Directory to obtain all the first names of every user. So I have created a new console application and in my main method have the following code:
try
{
DirectoryEntry myLdapConnection =new DirectoryEntry("virtual.local");
myLdapConnection.Path = "LDAP://DC=virtual,DC=local";
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.PropertiesToLoad.Add("cn");
SearchResultCollection allUsers = search.FindAll();
I have added some code to check that the connection is being made and that the path can be found. I also ensure that the Collection is not empty.
//For Debugging
if(DirectoryEntry.Exists(myLdapConnection.Path())
{
Console.WriteLine("Found");
}
else Console.WriteLine("Could Not Find LDAP Connection");
//In my case prints 230
Console.WriteLine("Total Count: " + allUsers.Count);
foreach(SearchResult result in allUsers)
{
//This prints out 0 then 1
Console.WriteLine("Count: " + result.Properties["cn'].Count);
if (result.Properties["cn"].Count > 0) //Skips the first value
{
Console.WriteLine(String.Format("{0,-20} : {1}",
result.Properties["cn"][0].ToString())); //Always fails
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
I have specified in the code, where it prints out the properties, that it always fails. I get a System.FormatException being caught here that states the Index must be greater than zero and less than the size of the argument list.
So in the end I'm not really sure how "result.Properties" works and was wondering if you had any advise on how to fix or troubleshoot the problem.
You are defining two format specifiers {0} and {1} but only specifying one argument.

Categories