GoogleDrive file multipart type upload in xamarin - xamarin

My Xamarin forms application uploads a zip file to google drive using rest apis.But the name is always displaying as "untitled".So I tried using multipart content,but got the parse error with "code": 400,
var jsonstring = "{ \"name\": \"demo.zip\” }";
var multicontent = new MultipartContent();
var strcontent = new StringContent(jsonstring);
var backupContent = “byte array content of my file”;
multicontent.Add(strcontent);
multicontent.Add(backupContent);
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer”, “my token value");
HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Length", backupContent.ContentLength.ToString());
HttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/related");
var res = await HttpClient.PostAsync( "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart", multicontent);
var stringContent = await res.Content.ReadAsStringAsync();

Based on the Google Drive documentation, The error 400: Bad Request that you got is a user error. This error is caused by:
required field or parameter has not been provided
the combination of provided fields is invalid
the value supplied in the parameter is invalid
Another caused of this error is when trying to add a duplicate parent to a Drive item. It can also be thrown when trying to add a parent that would create a cycle in the directory graph.
For more information, check this link to know the different upload options that you can do in Google Drive API. You can also check this ZIP Extractor if it can help you.

Related

How do I use Hl7.Fhir.Rest client to search for HealthCareService's

I am completely new to FHIR and have stumbled upon this NuGet package "Hl7.Fhir.STU3" and want to use it to search for Healthcare Services as defined here: https://digital.nhs.uk/developer/api-catalogue/e-referral-service-fhir#api-Default-a010-patient-service-search.
I so far have this limited code and understand I need to pass some form of search criteria but have no idea how to proceed. All I ever get back from the NHS client is:
"Root object has no type indication (resourceType) and therefore cannot be used to construct an FhirJsonNode. Alternatively, specify a nodeName using the parameter."
My code is:
var settings = new FhirClientSettings
{
Timeout = 10,
PreferredFormat = ResourceFormat.Json,
PreferredReturn = Prefer.ReturnMinimal,
};
var client = new FhirClient("https://sandbox.api.service.nhs.uk/referrals/FHIR/STU3/HealthcareService/$ers.searchHealthcareServicesForPatient", settings);
client.RequestHeaders.Add("Authorization", "Bearer g1112R_ccQ1Ebbb4gtHBP1aaaNM");
client.RequestHeaders.Add("nhsd-ers-ods-code", "R69");
client.RequestHeaders.Add("nhsd-ers-business-function", "REFERRING_CLINICIAN");
client.RequestHeaders.Add("X-Correlation-Id", Guid.NewGuid().ToString());
var services = client.Search<HealthcareService>();
I would really appreciate any assistance.
The URL you have set as your FHIR server endpoint is actually the URL for the operation call, so that will not work. If you set the server URL to "https://sandbox.api.service.nhs.uk/referrals/FHIR/STU3/", you should be able to use the FhirClient to do an operation call:
// Note that you have to send parameters in with your request, so set them up first:
var params = new Parameters();
params.Add("requestType", new Coding("https://fhir.nhs.uk/STU3/CodeSystem/eRS-RequestType-1", "APPOINTMENT_REQUEST"));
// etc...
var result = c.TypeOperation<HealthcareService>("ers.searchHealthcareServicesForPatient", params);
The $ sign in the original url is not part of the operation name, so I have omitted that in the request. The FhirClient will add the $ on the outgoing request.

Unable to view PDF attached with ServiceNow table records

I am able to successfully attach PDF file with ServiceNow table record using GlideSysAttachment API and attachment.write() function in script, however whenever I download and try to open same, I get the error shown in below screenshot.
Code snippet
(function execute() {
try{
var rec = new GlideRecord('incident');
var attachment = new GlideSysAttachment();
var incidentSysID = incident.number;
rec.get(incidentSysID);
var fileName = 'Test_Incident.pdf';
var contentType = 'application/pdf'; // Also tried with contentType as 'text/pdf'
var content = pdf_content;
var agr = attachment.write(rec, fileName, contentType, content);<br>
gs.info('The PDF attachment sys_id is: ' + agr);
}catch(err){
gs.log('Got Error: ' + err);
gs.info(err);
}
})()
I also tried "AttachmentCreator" with ecc_queue within script but same error occurs. Below is code for it.
(function execute()
{var attCreator = new GlideRecord('ecc_queue');
attCreator.agent = "AttachmentCreator";
attCreator.topic = "AttachmentCreator";
attCreator.name = "Test.pdf" + ":" + "text/pdf";
//Also tried, "Test.pdf:application/pdf"
attCreator.source = "incident"+":"+ incident.number;
// Record Table name and sys_id of the particular record
var content = pdf_content; // pdf_content is any string variable
var stringUtil = new GlideStringUtil();
var base64String = stringUtil.base64Encode(content);
var isValid=GlideStringUtil.isBase64(base64String);
var base64String= gs.base64Encode(content);
gs.info("Is valid base64 format in ecc_queue ? "+ isValid);
attCreator.payload = base64String; //base64 content of the file
attCreator.insert();
})()
I am able to attach and view excel and word files with similar scripts without any issues. I have checked system properties for attachments but everything looks fine. I am able to view the PDF file uploaded from UI to particular table records however not the one I attach via REST API or scripts.
I have also tried sending encoded data as bytes, base64 or simple string but nothing seems to work. I don't get any errors and attachment id is returned each time on creation of attachment.
After modifying my code slightly for above functions w.r.t scoped application instead of global; I got some information from logs when I debug:
05:38:38.411 Security restricted: File type is not allowed or does not match the content for file Test.pdf
05:38:38.410 Security restricted: MIME type mismatch for file: Test.pdf. Expected type:application/pdf, Actual type: text/plain
05:38:38.394 App:XYZ App x_272539_xyz_ap: Is valid base64 format in ecc_queue ? true
First a comment: This line in your code is accidentally working -- make sure you understand that a task number is not the object sys_id
var incidentSysID = incident.number; // should be incident.sys_id
Next, it's unclear where the PDF content is coming from. IF your complete code is listed, I would expect the errors given as you have noted that pdf_content is "any string variable."
ServiceNow does have a the capability to create a PDF from an HTML argument.
Generating a PDF from HTML
Here's a helpful blog post for getting a PDF (Platform generated) of an existing record:
Love PDF? PDF loves you too

EWS Managed API 2, setting FlagStatus

I'm attempting to set the Flag on an e-mail using EWS Managed API 2 - however, I keep getting an error that I can't seem to get past.
I'm doing the following:
ExchangeService exchangeService = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
exchangeService.Url = new Uri(<ews url comes from Outlook JavaScript API>);
exchangeService.UseDefaultCredentials = false;
exchangeService.Credentials = new OAuthCredentials(<ews token comes from Outlook JavaScript API>);
And then a little later:
Item item = Item.Bind(exchangeService, new ItemId(<mail id comes from Outlook JavaScript API>), new PropertySet(ItemSchema.Flag));
item.Load();
item.Flag = new Flag() { FlagStatus = ItemFlagStatus.Flagged };
item.Update(ConflictResolutionMode.AutoResolve);
What am I missing?
I keep getting this error:
You must load or assign this property before you can read its value.
UPDATE: Ok, it turned out the this error was caused by some other code which has been corrected.
Now I'm getting this error instead:
The requested web method is unavailable to this caller or application.

Flutter: Copy image file from url to firebase

I'm trying to copy a user profile picture from an external service onto my firebase server. So far I have:
final File file = await new File.fromUri(Uri.parse(auth.currentUser.photoUrl)).create();
final StorageReference ref = FirebaseStorage.instance.ref().child("profile_image_${auth.currentUser.uid}.jpg");
final StorageUploadTask uploadTask = ref.put(file);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;
// add user profile picture url to user object
final userReference = FirebaseDatabase.instance
.reference()
.child('users/' + auth.currentUser.uid);
userReference.set({'photoUrl': downloadUrl});
The very top line gives me the error: Unsupported operation: Cannot extract a file path from a https URI
What is the correct way to do this? Should this even be done client-side? (Should I just be passing this url to firebase and use a function to download it server-side?)
File only supports files on a file system.
To load content using HTTP use the http package.
See also https://flutter.io/networking/
var httpClient = createHttpClient();
var response = await httpClient.get(url);
and then get the data from response.body,
or
var response = await httpClient.readBytes(url);
to get it as binary (Uint8List)
See also https://www.dartdocs.org/documentation/http/0.11.3+14/http/Client-class.html

Receiving null parameters from request in JSP file when are being sent

I've a JSP app. It uploads a file, but to do so the user has to authenticate using a name and a password. So my JSP file starts with:
//0.2.- We get the password
String password = (String) request.getParameter("pass"); // -> This returns NULL
//0.3.- We get the "uvus"
String uvus = (String) request.getParameter("uvus"); //-> This also returns NULL
//More code
So I'm trying to know why am I getting null from those variables.
I went to the form I was uploading, and look for the data that was being sent. Using Firefox Debug Tools, I saw:
So in fact, it was being sent.
As additional info, I'm building the request like this:
var pUvus = document.getElementById("uvus").value;
var pPassword = document.getElementById("pass").value;
var file = document.getElementById("userFile");
var formData = new FormData();
formData.append("upload", file.files[0]);
formData.append("uvus", pUvus);
formData.append("pass", pPassword);
xmlhttp.open("POST","uploadFile.jsp",true);
xmlhttp.send(formData);
At last, I would like to say that I can get vars from application object in the same JSP with no errors, and have received in another pair of JSP files vars at request object without more problems, so I think my fault should be in the way I'm building the request in Ajax, but I've no more clue about that...
Anyone can guide me?
Thanks for your help
Update: #rickz asked for how do I get the file and parse the request (what is done after my problem, trying to get the objects from the request scope):
List items;
items = servlet_up.parseRequest(request);
for(int i=0;i<items.size();i++)
{
FileItem item = (FileItem) items.get(i);
if (! item.isFormField())
{
request.getParameter() won't work for a multipart/form-data request.
If you are using org.apache.commons.fileupload then you should be using something like
if(item.isFormField()){
name = item.getFieldName();
...
}

Resources