C++/CX Metro Windows - create_task implementation prevents using variable not defined in that scope - windows

I am trying to define Uri^ outside of the implementation of create_task. In java, if you have an asynchronous task adding the final modifier would allow you to use that variable (with final modifier) inside the asynchronous code.
How can I use Uri^ source from the below code inside the asynchronous code?
void addDownload(Uri^ source, StorageFolder^ destinationFolder, String^ fileName) {
boolean requestUnconstrainedDownload = false;
IAsyncOperation<StorageFile^>^ asyncOperationStorageFile = destinationFolder->CreateFileAsync(fileName, CreationCollisionOption::GenerateUniqueName);
auto createStorageFileTask = create_task(asyncOperationStorageFile);
createStorageFileTask.then([] (StorageFile^ destinationFile) {
BackgroundDownloader^ downloader = ref new BackgroundDownloader();
DownloadOperation^ downloadOperation = downloader->CreateDownload(source, destinationFile);
downloadOperation->Priority = BackgroundTransferPriority::Default;
HandleDownloadAsync(downloadOperation, true);
});
}

Just capture the variable source in the lambda so it can be accessed in the lambda body of the task:
void addDownload(Uri^ source, StorageFolder^ destinationFolder, String^ fileName) {
boolean requestUnconstrainedDownload = false;
IAsyncOperation<StorageFile^>^ asyncOperationStorageFile = destinationFolder->CreateFileAsync(fileName, CreationCollisionOption::GenerateUniqueName);
auto createStorageFileTask = create_task(asyncOperationStorageFile);
createStorageFileTask.then([source] (StorageFile^ destinationFile) {
BackgroundDownloader^ downloader = ref new BackgroundDownloader();
DownloadOperation^ downloadOperation = downloader->CreateDownload(source, destinationFile);
downloadOperation->Priority = BackgroundTransferPriority::Default;
HandleDownloadAsync(downloadOperation, true);
});
}

Related

Radzen Blazor DropDown on dynamic data from external API

I'm getting data from an external API and the code looks like this (this part is fine):
#code {
IEnumerable<IDictionary<string, object>> data;
int count;
bool isLoading;
async Task LoadData(LoadDataArgs args)
{
isLoading = true;
var uri = new Uri("https://services.radzen.com/odata/Northwind/Employees")
.GetODataUri(filter: args.Filter, top: args.Top, skip: args.Skip, orderby: args.OrderBy, count: true);
var response = await new HttpClient().SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
var result = await response.ReadAsync<ODataServiceResult<IDictionary<string, object>>>();
data = result.Value.AsODataEnumerable();
count = result.Count;
isLoading = false;
}
}
On the dropdown menu I want to display the EmployeeID, but cannot access it (the Data="#data.Employee.ID" is incorrect and not sure what to put in there to make it work).
<RadzenDropDown Data="#data.EmployeeID" TextProperty="EmployeeID" ValueProperty="EmployeeID" Name="Dropdown1" TValue="string">
</RadzenDropDown>
Thanks!
The problem is that the Data Property is:
IEnumerable<IDictionary<string, object>> data;
It should be:
IEnumerable<Employee>data;
So then you can acess to Employee class properties.
<RadzenDropDown Data="#data.EmployeeID" TextProperty="EmployeeID" ValueProperty="EmployeeID" Name="Dropdown1" TValue="Employee">
</RadzenDropDown>

No appropriate font found using MigraDoc to create a PDF on Xamarin Forms

I'm trying to create a pdf using MigraDoc. Here's a list of the libraries that I'm using:
MigraDoc.DocumentObjectModel
MigraDoc.DocumentObjectModel.Tables
MigraDoc.Rendering
It throws me an error on printer.RenderDocument(). Code below
private async Task SavePDF()
{
filePath = emulatorFolderPath + "/Signed/" + _reportInformationViewModel.SelectedClient.Username + "-" + DateTime.Now.ToString("dd_MM_yyyy HH-mm") + ".pdf";
MigraDocRendering.PdfDocumentRenderer printer = new MigraDocRendering.PdfDocumentRenderer
{
Document = document
};
printer.RenderDocument();
printer.PdfDocument.Save(filePath);
}
PS: I don't need to use a private font.
I've resolved by implementing IFontResolver
I've added a folder Fonts that contains Open-Sans font.
I've created a folder Helpers that contains a class called GenericFontResolver:
public class GenericFontResolver : IFontResolver
{
public string DefaultFontName => "OpenSans";
public byte[] GetFont(string faceName)
{
if (faceName.Contains(DefaultFontName))
{
var assembly = typeof(ReportPreviewAndSignatureViewModel).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream($"PDFDemo.Fonts.{faceName}.ttf");
using (var reader = new StreamReader(stream))
{
var bytes = default(byte[]);
using (var ms = new MemoryStream())
{
reader.BaseStream.CopyTo(ms);
bytes = ms.ToArray();
}
return bytes;
}
}
else
return GetFont(DefaultFontName);
}
public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
{
var fontName = string.Empty;
switch (familyName)
{
case "Open Sans":
case "OpenSans":
fontName = "OpenSans";
if (isBold && isItalic)
fontName = $"{fontName}-BoldItalic";
else if (isBold)
fontName = $"{fontName}-Bold";
else if (isItalic)
fontName = $"{fontName}-Italic";
else
fontName = $"{fontName}-Regular";
return new FontResolverInfo(fontName);
default:
break;
}
return null;
}
}
Then, on the constructor of the class that needs the font I've added:
GlobalFontSettings.FontResolver = new GenericFontResolver();
Then, when I'm creating the table you must add:
Style style = document.Styles["Normal"];
style.Font.Name = "OpenSans";

Syntax help for creating a filter in aws ec2 describeinstance api call in c++

Using DescribeInstancesRequest (c++ sdk) to get response about a particular instance_id. I am having a problem constructing the filter.
I am adapting the example code provided by the aws-doc-sdk-examples c++ example code describe_instances.cpp. I have added code to filter the response to use a known valid (now hard coded) instance ID.
I have tried multiple variations to set up the filter, but the docs aren't clear to me about the "value pair" format for the filter.
Here is the complete code. It compiles just find, but always responds with the "Could not find: ..."
Please let me know what I am getting wrong with the filter syntax! (See commented section Filter an instance id)
Thanks
void Server::set_instance_info()
{
// Get server instance information via aws sdk
Aws::SDKOptions options;
Aws::InitAPI(options);
{
/* #TODO Make this a startup config value */
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = "us-west-2";
Aws::EC2::EC2Client ec2(clientConfig);
Aws::EC2::Model::DescribeInstancesRequest request;
// Filter an instance_id
Aws::EC2::Model::Filter filter;
filter.SetName("instance_id");
Aws::String filter_val{"Name=instance_id,Values=i-0e120b44acc929946"};
Aws::Vector<Aws::String> filter_values;
filter_values.push_back(filter_val);
filter.SetValues(filter_values);
Aws::Vector<Aws::EC2::Model::Filter> DIRFilter;
DIRFilter.push_back(filter);
request.SetFilters(DIRFilter);
auto outcome = ec2.DescribeInstances(request);
if (outcome.IsSuccess())
{
const auto &reservations =
outcome.GetResult().GetReservations();
for (const auto &reservation : reservations)
{
const auto &instances = reservation.GetInstances();
for (const auto &instance : instances)
{
Aws::String instanceStateString =
Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName(
instance.GetState().GetName());
Aws::String type_string =
Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType(
instance.GetInstanceType());
Aws::String name = "Unknown";
const auto &tags = instance.GetTags();
auto nameIter = std::find_if(tags.cbegin(), tags.cend(),
[](const Aws::EC2::Model::Tag &tag)
{
return tag.GetKey() == "Name";
});
if (nameIter != tags.cend())
{
name = nameIter->GetValue();
}
Server::id_ = instance.GetInstanceId();
Server::name_ = name;
Server::type_ = type_string;
Server::dn_ = "Not implemented";
Server::ip_ = "Not implmented";
}
}
} else {
Server::id_ = "Could not find: " + filter_val;;
Server::name_ = "";
Server::type_ = "";
Server::dn_ = "";
Server::ip_ = "";
}
}
return;
}
I just couldn't get the filter to work. Any input would be appreciated. However, there is an alternate method using the WithInstanceIds member function. Reading the API docs is always a good idea!!
Here is the subroutine that works:
void Server::set_instance_info()
{
// Get server instance information via aws sdk
Aws::SDKOptions options;
Aws::InitAPI(options);
{
/* #TODO Make this a startup config value */
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = "us-west-2";
Aws::EC2::EC2Client ec2(clientConfig);
Aws::EC2::Model::DescribeInstancesRequest request;
/* #TODO Make this a startup config value */
const Aws::String instanceId{"i-0e120b44acc929946"};
Aws::Vector<Aws::String> instances;
instances.push_back(instanceId);
request.WithInstanceIds(instances);
auto outcome = ec2.DescribeInstances(request);
if (outcome.IsSuccess())
{
const auto &reservations =
outcome.GetResult().GetReservations();
for (const auto &reservation : reservations)
{
const auto &instances = reservation.GetInstances();
for (const auto &instance : instances)
{
Aws::String instanceStateString =
Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName(
instance.GetState().GetName());
Aws::String type_string =
Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType(
instance.GetInstanceType());
Aws::String name = "Unknown";
const auto &tags = instance.GetTags();
auto nameIter = std::find_if(tags.cbegin(), tags.cend(),
[](const Aws::EC2::Model::Tag &tag)
{
return tag.GetKey() == "Name";
});
if (nameIter != tags.cend())
{
name = nameIter->GetValue();
}
Server::id_ = instance.GetInstanceId();
Server::name_ = name;
Server::type_ = type_string;
Server::dn_ = "Not implemented";
Server::ip_ = "Not implmented";
}
}
} else {
Server::id_ = "Could not find: "+ instanceId;
Server::name_ = "";
Server::type_ = "";
Server::dn_ = "";
Server::ip_ = "";
}
}
return;
}

WebAPI HttpContext is Null Inside ContinueWith() => tast

I'm just wondering if someone could explain what is happening here.
Given this Post method on an API controller:
public HttpResponseMessage PostImage()
{
var request = HttpContext.Current.Request;
var c = SynchronizationContext.Current;
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (Request.Content.IsMimeMultipartContent())
{
Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider()).ContinueWith((task) =>
{
MultipartMemoryStreamProvider provider = task.Result;
foreach (HttpContent content in provider.Contents)
{
Stream stream = content.ReadAsStreamAsync().Result;
Image image = Image.FromStream(stream);
var uploadFileName = content.Headers.ContentDisposition.FileName;
var requestInside = HttpContext.Current.Request; // this is always null
string filePath = Path.Combine(HostingEnvironment.MapPath(ConfigurationManager.AppSettings["UserFilesRootDir"]), userprofile.UserCode);
//string[] headerValues = (string[])Request.Headers.GetValues("UniqueId");
string fileName = userprofile.UserCode + ".jpg";
string fullPath = Path.Combine(filePath, fileName);
image.Save(fullPath);
}
});
return result;
}
}
Why would var requestInside = HttpContext.Current.Request; be null?
I've checked all the relevant settings:
<compilation debug="true" targetFramework="4.5">
...
<httpRuntime targetFramework="4.5"
And SynchronizationContext.Current is the newer AspNetSynchronizationContext rather than LegacyAspNetSynchronizationContext.
I'm presuming at the moment that it's because I'm on a different thread, is this a correct assumption?
ContinueWith is not guaranteed to run on the same thread hence the synchronization context could be lost. You could change your call to specify to resume on the current thread with parameter TaskScheduler.Current. See this previous SO answer.
If you use await/async pattern it will automatically capture the current syncronization context on resume once an awaitable operation completes. This is done by resuming the operation on the same thread which is bound to that context. An added benefit, IMHO, is cleaner looking code.
You can change your code to this which uses that pattern. I have not made any other changes to it other than use async/await.
public async Task<HttpResponseMessage> PostImage()
{
var request = HttpContext.Current.Request;
var c = SynchronizationContext.Current;
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (Request.Content.IsMimeMultipartContent())
{
MultipartMemoryStreamProvider provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
foreach (HttpContent content in provider.Contents)
{
Stream stream = await content.ReadAsStreamAsync();
Image image = Image.FromStream(stream);
var uploadFileName = content.Headers.ContentDisposition.FileName;
var requestInside = HttpContext.Current.Request; // this is always null
string filePath = Path.Combine(HostingEnvironment.MapPath(ConfigurationManager.AppSettings["UserFilesRootDir"]), userprofile.UserCode);
//string[] headerValues = (string[])Request.Headers.GetValues("UniqueId");
string fileName = userprofile.UserCode + ".jpg";
string fullPath = Path.Combine(filePath, fileName);
image.Save(fullPath);
}
}
return result;
}

What arguments should be passed to Asychronous functions

I am new to unit testing. How can I pass arguments into the below function
OnDefineInDictCompleted
client.DefineInDictCompleted += new EventHandler<DefineInDictCompletedEventArgs>(OnDefineInDictCompleted);
OnDefineInDictCompleted(object sender, DefineInDictCompletedEventArgs e)
Rather than define OnDefineInDictCompleted as a method how about using anonymous delegates?
var parameterA = 1;
var parameterB = "Foo";
EventHandler<DefineInDictCompletedEventArgs> handler = (s, e) =>
{
//Can access local variables here;
var x = parameterA.ToString() + parameterB;
};
client.DefineInDictCompleted += handler;

Resources