WP: Can please give explaination what token is in GetPathFromToken - windows-phone-8

The MediaLibraryExtensions.GetPathFromToken has 2 parameters (MediaLibrary library, string token) as input. I assume the API returns path of specified media item from media library, The token is associated with the media of interest. However, how do I find out the "token" of the media, say a music file in media library? Could please show me how to figure out the "token" from a given Song? Thanks in advance.

The value of Token is supplied to an application on a query string when that application is registered to extend various parts of the Windows Phone OS, this includes Photo Share Picker, Photo Edit Picker and Auto Launch from a File Association
All the examples use GetPictureFromToken, but you can imagine the same scenario with other media types being 'Launched' via file association.
Here's a sample of how to use token with GetPicturesFromToken
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// Get a dictionary of query string keys and values.
IDictionary<string, string> queryStrings = this.NavigationContext.QueryString;
// Ensure that there is at least one key in the query string, and check whether the "token" key is present.
if (queryStrings.ContainsKey("token"))
{
// Retrieve the photo from the media library using the token passed to the app.
MediaLibrary library = new MediaLibrary();
Picture photoFromLibrary = library.GetPictureFromToken(queryStrings["token"]);
// Create a BitmapImage object and add set it as the image control source.
BitmapImage bitmapFromPhoto = new BitmapImage();
bitmapFromPhoto.SetSource(photoFromLibrary.GetImage());
image1.Source = bitmapFromPhoto;
}
}
GetPathFromToken should behave in the same way.

Related

Get Revit Workshared cloud model as C# Autodesk.Revit.DB Document class

I have a Revit plug-in, I want it to do some operations on a workshared cloud model.
I can't figure out how to get the Revit model as a Document class (Autodesk.Revit.DB)
which is stored live on BIM360 cloud, not a local copy, nor downloaded copy.
Seems like I have to use different API's and there are multiple steps to this although
I was expecting something relatively simpler, I quickly realised this actually may have
multiple steps which I honestly can't figure out.
Is there a working relevant code example on git hub for this ?
Edit: I was able to find the below code but it doesn't compile
because ForgeClient and OSSObjectsApi doesn't exist in the latest
forge sdk package, how can I fix that ?
using System;
using System.IO;
using System.Threading.Tasks;
using Autodesk.Forge;
using Autodesk.Forge.Model;
using Autodesk.Forge.Client;
using Newtonsoft.Json.Linq;
namespace BIM360Downloader
{
class Program
{
static void Main(string[] args)
{
// These are the client ID and client secret that you obtained
// when you registered your application on the Forge developer portal.
string clientId = "YOUR_CLIENT_ID";
string clientSecret = "YOUR_CLIENT_SECRET";
// Replace these with the project ID and file ID of the model you want to download.
string projectId = "YOUR_PROJECT_ID";
string fileId = "YOUR_FILE_ID";
// Create a new Forge API client.
ForgeClient client = new ForgeClient(clientId, clientSecret);
// Get the access token for the client.
TwoLeggedApi oauth = new TwoLeggedApi();
dynamic token = oauth.Authenticate(clientId, clientSecret, "client_credentials", new Scope[] { Scope.DataRead });
string accessToken = token.access_token;
// Set the bearer token for the client.
client.Configuration.AccessToken = accessToken;
// Download the model from BIM 360.
MemoryStream modelStream = DownloadModelAsync(client, projectId, fileId).Result;
Console.WriteLine("Successfully downloaded model to memory stream.");
}
static async Task<MemoryStream> DownloadModelAsync(ForgeClient client, string projectId, string fileId)
{
// Set up the request to download the model.
OSSObjectsApi objectsApi = new OSSObjectsApi();
dynamic objectDetails = await objectsApi.GetObjectDetailsAsync(projectId, fileId);
string bucketKey = objectDetails.bucketKey;
// Download the model data.
dynamic data = await objectsApi.GetObjectAsync(bucketKey, fileId);
byte[] modelData = data.Body;
// Create a new MemoryStream object to store the model data.
MemoryStream modelStream = new MemoryStream(modelData);
return modelStream;
}
}
}
To open a live Revit Could Model (RCM), you can use ModelPathUtils.ConvertCloudGUIDsToCloudPath() to convert the project and model guid into a ModelPath. You can then use this ModelPath to open the document using Application.OpenDocumentFile() method.
Also read the sections Getting the CloudPath for a Model and SaveAsCloudModel Information from the Web Browser in this link on how to find the account, project, and model guids of the model you are interested in.
var cloudModelPath = ModelPathUtils.ConvertCloudGUIDsToCloudPath(region, projectGuid, modelGuid);
Document doc = app.OpenDocumentFile(cloudModelPath, new OpenOptions());
This code will work in a desktop addin as long as a valid user is logged in and that user has access to the input model. While you have not explicitly mentioned that you need this to work on Design Automation for Revit, you have added the tag #autodesk-designautomation to your question. The good news is the same code above should work for Design Automation addin (app bundle), but there is an extra step on how to provide user context to the design automation job. Please refer to this blog post and github sample for Design Automation for RCM.

PostAsJsonAsync not calling the Controller when <Tvalue> has null fields

My TValue object has foreign key related objects, which has null values when posting; I am having the logic to set the FK objects in the repository. The issue I am facing is that API controller is not getting called when FK objects have all fields null. Please see screenshot. The same code works if I set the value for all but the ID field of the FK objects from the front end.
Is the issue because Json serializer checking for nulls? I have also tried to set the null check ignore option. I am not getting an error on PostAsJsonAsync and the control simply goes to the next line of code
return await result.Content.ReadFromJsonAsync();
without calling the API controller and send an exception
public async Task<SubContract> AddSubContract(SubContract subContract)
{
/* On the injected httpClient, call the PostAsJsonAsync method and pass the subContractObject
* We also need to specifi the api Uri in the parameter list */
JsonSerializerOptions option = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
var result = await httpClient
.PostAsJsonAsync<SubContract>("api/SubContracts", subContract, option);
//Use the content object and ReadFromJsonSync method and typecast it to <SubContract>
return await result.Content.ReadFromJsonAsync<SubContract>();
}
Screenshot
--- Further observations ---
#Serge Thanks for the response. You are right, I am using .Net 6. I have now commented out the nullable but I still have the same issue. Further, I tried to change the function to PostAsync instead of PostAsJsonAsync; below is the new code
// ---- Post Asysc Option -----
var subContractSeralized = JsonSerializer.Serialize(subContract, option);
var stringContent = new StringContent(subContractSeralized,
encoding: System.Text.Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("api/subcontract", stringContent);
return await response.Content.ReadFromJsonAsync<SubContract>();
I initially thought it was a serialization issue because of the nulls in the nested object but when I debug the new code, I get the below result
subContractSerealized = '{"Id":0,"Name":"Aquatic-Repairs","Status":"In-Progress","WorkTypeId":1002,"WorkType":{"Id":0},"SiteId":3,"Site":{"Id":0},"OrganizationId":3,"Organization":{"Id":0}}'
If you compare this with the Debug screen shot in my first post, you can see that the null value fields in the nested objects are omitted out
Response StatusCode = “Not Found-404”
I am not sure how Response Status code is obtained as the API is not called. I.e. httpClient.PostAsync does not transfer control to the API and my debug breakpoint is not hit.
I tried the same code for an Entity model that has no nested foreign key related objects and it works fine and I am able to add the record to the DB. I have the “Required” validation set on the field properties of the entity models; however, after the API call, I have my repository that is taking care of it. So, I doubt that is an issue. In any case, the code is not even hitting the API and simply returns an 404 NotFound on httpClient.PostAsync.
you must be using Net 6 API, and it causes a validation error. Try to comment Nullable in your API project (your serializer option is not working in this case)
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<!--<Nullable>enable</Nullable>-->
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

Dynamic parameter as part of request URI with Apache HttpCore

I am looking for existing solutions to match dynamic parameters with HttpCore. What I have in mind is something similar to constraints in ruby on rails, or dynamic parameters with sails (see here for example).
My objective is to define a REST API where I could easily match requests like GET /objects/<object_id>.
To give a little bit of context, I have an application that creates an HttpServer using the following code
server = ServerBootstrap.bootstrap()
.setListenerPort(port)
.setServerInfo("MyAppServer/1.1")
.setSocketConfig(socketConfig)
.registerHandler("*", new HttpHandler(this))
.create();
And the HttpHandler class that matches the requested URI and dispatches it to the corresponding backend method:
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT);
// Parameters are ignored for the example
String path = request.getRequestLine().getUri();
if(method.equals("POST") && path.equals("/object/add") {
if(request instanceof HttpEntityEnclosingRequest) {
addObject(((HttpEntityEnclosingRequest)request).getEntity())
}
[...]
For sure I can replace path.equals("/object/add") by something more sophisticated with RegEx to match these dynamic parameters, but before doing so I'd like to know if I am not reinventing the wheel, or if there is an existing lib/class I didn't see in the docs that could help me.
Using HttpCore is a requirement (it is already integrated in the application I am working on), I know some other libraries provide high-level routing mechanisms that support these dynamic parameters, but I can't really afford switching the entire server code to another library.
I am currently using httpcore 4.4.10, but I can upgrade to a newer version of this might help me.
At present HttpCore does not have a fully featured request routing layer. (The reasons for that are more political than technical).
Consider using a custom HttpRequestHandlerMapper to implement your application specific request routing logic.
final HttpServer server = ServerBootstrap.bootstrap()
.setListenerPort(port)
.setServerInfo("Test/1.1")
.setSocketConfig(socketConfig)
.setSslContext(sslContext)
.setHandlerMapper(new HttpRequestHandlerMapper() {
#Override
public HttpRequestHandler lookup(HttpRequest request) {
try {
URI uri = new URI(request.getRequestLine().getUri());
String path = uri.getPath();
// do request routing based on the request path
return new HttpFileHandler(docRoot);
} catch (URISyntaxException e) {
// Provide a more reasonable error handler here
return null;
}
}
})
.setExceptionLogger(new StdErrorExceptionLogger())
.create();

Xamarin Forms - Saving object to access it later

I am using Xamarin Forms with Newtonsoft.JSON and Xam.Plugin.Settings plugins to save IDevice object as JSON to use it later.
First page:
private async void SelectBluetoothDevice(object sender, SelectedItemChangedEventArgs e)
{
string device = JsonConvert.SerializeObject((IDevice) e.SelectedItem);
AppSettings.AddOrUpdateValue("device", device);
await Navigation.PopAsync();
}
Here I simply make selected item to JSON string and save it. It works like it should be.
But the problem im facing comes whenever I try to deserialize from saved string.
string device = AppSettings.GetValueOrDefault("device", "");
if (!device.Equals(""))
{
Debug.WriteLine(device);
// This line produces error
IDevice dev = JsonConvert.DeserializeObject<IDevice>(device);
settingsDeviceName.Text = dev.Name;
}
Newtonsoft.Json.JsonSerializationException: Could not create an
instance of type Plugin.BLE.Abstractions.Contracts.IDevice. Type is an
interface or abstract class and cannot be instantiated. Path
'BluetoothDevice', line 1, position 19.
So I understand that IDevice is interface and my JSON string cant be deserialized nothing but into object. Any good ideas how to workaround it? Thanks!
This line JsonConvert.DeserializeObject<IDevice>(device); basically does this:
Read the JSON in device
Try to create the type of object you want to deserialize to, in this case, IDevice
Return you the new object with all the properties filled
The problem is with step 2. You can't create an instance of an interface. So you need to deserialize to a concrete object that implements IDevice.

Is there a way to store instances of own classes in the ApplicationSettings of a Windows Store app?

In a Windows Store app I can only store WinRT types in the ApplicationSettings, according to the documentation. For roamed settings that should be held together I can use ApplicationDataCompositeValue. Trying to store an instance of an own class or struct results in an Exception with the message " WinRT information: Error trying to serialize the value to be written to the application data store. Additional Information: Data of this type is not supported". The term "trying to serialize" indicates that there must be some way so serialize a type for the application data API.
Does anyone know how I could achieve that?
I tried DataContract serialization but it did not work.
I think custom/own types are not supported.
See http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx:
"The Windows Runtime data types are supported for app settings."
But you can serialize your objects to XML and save as string... (see code below)
public static string Serialize(object obj)
{
using (var sw = new StringWriter())
{
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
return sw.ToString();
}
}
public static T Deserialize<T>(string xml)
{
using (var sw = new StringReader(xml))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(sw);
}
}
https://github.com/MyToolkit/MyToolkit/blob/master/src/MyToolkit/Serialization/XmlSerialization.cs
Check out this class too:
https://github.com/MyToolkit/MyToolkit/wiki/XmlSerialization
Disclaimer: The above links are from my project