my first question is here
however since I was advised that questions should not change the original matter I created a new one.
I am saving user settings and I would like to save it in the list, I have had a look on setting by James however I found that that its not possible to save it in the list. So ia have decided to use Xamarin Essentials.
First I tried to save only a string value, which after some struggle I managed to work out and now I am trying to save an object
static void AddToList(SettingField text)
{
var savedList = new List<SettingField>(Preference.SavedList);
savedList.Add(text);
Preference.SavedList = savedList;
}
private void ExecuteMultiPageCommand(bool value)
{
var recognitionProviderSettings = new RecognitionProviderSettings
{SettingFields = new List<SettingField>()};
var set = new SettingField()
{
ProviderSettingId = "test",
Value = "test"
};
AddToList(set);
NotifyPropertyChanged("IsMultiPage");
}
and then the sterilization and des
public static class Preference
{
private static SettingField _settingField;
public static List<SettingField> SavedList
{
get
{
//var savedList = Deserialize<List<string>>(Preferences.Get(nameof(SavedList), "tesr"));
var savedList = Newtonsoft.Json.JsonConvert.DeserializeObject<SettingField>(Preferences.Get(nameof(SavedList), _settingField)) ;
SavedList.Add(savedList);
return SavedList ?? new List<SettingField>();
}
set
{
var serializedList = Serialize(value);
Preferences.Set(nameof(SavedList), serializedList);
}
}
static T Deserialize<T>(string serializedObject) => JsonConvert.DeserializeObject<T>(serializedObject);
static string Serialize<T>(T objectToSerialize) => JsonConvert.SerializeObject(objectToSerialize);
}
}
But Preferences.Get doesn't take object, is there any other way how can I save my setting to a object list? Please advise
I would recommend you to use SecureStorage. You can save your strings only into it. So the place where you have serilized your object as json. Just convert your json to string with .ToString() and save it into secure storage.
You may continue saving your serialized json object as string in Shared preferences but it is recommended to use SecureStorage Instead.
So, we have created many templates using handlebars. Out of the many, we have one handlebar where we would like to make some changes that should only go live after a certain date. To do so, we wanted to create sort of a toggle switch, something like:
{{if switch on}}
display new content
{{else}}
display old content
Below is the generic template parser where I am trying to create a switch that I can inject in the if part of my template. Any suggestions?
/**
* Creates HTML output of the specified context for the given templateId and templateVersion combination
* we implicitly assume certain json fields (template specific) to be present in the content
*/
#Timed("handlebarsService.parseTemplateToHtml")
fun parseTemplateToHtml(htmlTemplateLocation: String, model: Map<String, Any>, locale: Locale): String {
val modelWithLanguage = model.toMutableMap()
modelWithLanguage[languageTag] = locale.language
//modelWithLanguage[switch] = "off"
val context = Context.newBuilder(modelWithLanguage)
.resolver(MapValueResolver.INSTANCE)
.build()
val template = try {
handlebars.compile(htmlTemplateLocation)
} catch (e: IOException) {
throw PdfGenerationException(e, "Internal error while compiling template")
}
return try {
template.apply(context)
} catch (e: IOException) {
throw PdfGenerationException(e, "Internal error while applying template")
}
}
}
private const val languageTag = "languageTag"
//private const val switch ="off"
I'm beginner with these Google's products and got 'serious' problem.
I uploaded photos and videos to firebase storage and urls of the photos and videos in the firebase storage is generated and stored automatically in firebase database. In my flutter lib, I could call those urls by my own code and display the url's image on the avd screen.
Image.network(url) is the code to display image url from firebase. But I also wanna display video url's asset simultaneously with single code. That is, videos and photos should be in single screen! In this case, Image.network(url) doesn't work anymore..
If I change that image.network code for video format according to video_player plug-in, I cannot display image asset anymore and if I stay same with that Image.network(url) code, I cannot display video url from firebase. So here is the question:
How can I detect whether the firebase's url string is image or video with my flutter code, and display that asset on the 'single screen' whatever the file format is(at least video and photo) with integrated flutter code?
url example
It's not much of a deal since type of the media is in the URL. You can parse it as a
Uri object then extract the type.
import 'dart:core';
enum UrlType { IMAGE, VIDEO, UNKNOWN }
void main() async {
var imageUrl =
'https://firebasestorage.googleapis.com/v0/b/myAppCodeNameForFirebase.appspot.com/o/Posts%20Pictures%2Fiufri095620200814.jpg?alt=media&token=89b6c22f-b8dd-4cff-9395-f53fc0808824';
var videoUrl =
'https://firebasestorage.googleapis.com/v0/b/myAppCodeNameForFirebase.appspot.com/o/Posts%20Pictures%2Fiufri095620200814.mp4?alt=media&token=89b6c22f-b8dd-4cff-9395-f53fc0808824';
print(getUrlType(imageUrl));
print(getUrlType(videoUrl));
}
UrlType getUrlType(String url) {
Uri uri = Uri.parse(url);
String typeString = uri.path.substring(uri.path.length - 3).toLowerCase();
if (typeString == "jpg") {
return UrlType.IMAGE;
}
if (typeString == "mp4") {
return UrlType.VIDEO;
} else {
return UrlType.UNKNOWN;
}
}
Let me give you an idea.
Consider implementing this scenario.
var url = 'domain.com/file.jpg?querySegment';
In your widget area,
child: url.contains('.mp4?') ? VideoWidget() : ImageWidget()
also, even with multiple conditions,
child: (url.contains('.jpg?') || url.contains('.png?')) ? ImageWidget() : VideoWidget()
May this suits your case.
Improving upon the accepted answer, here is what I have in my code. I needed a way to identify many types of videos and images from the passed url.
Using path package to idetify the extension
Have a list of video and image extension
import 'package:path/path.dart' as p;
enum UrlType { IMAGE, VIDEO, UNKNOWN }
class UrlTypeHelper {
static List<String> _image_types = [
'jpg',
'jpeg',
'jfif',
'pjpeg',
'pjp',
'png',
'svg',
'gif',
'apng',
'webp',
'avif'
];
static List<String> _video_types = [
"3g2",
"3gp",
"aaf",
"asf",
"avchd",
"avi",
"drc",
"flv",
"m2v",
"m3u8",
"m4p",
"m4v",
"mkv",
"mng",
"mov",
"mp2",
"mp4",
"mpe",
"mpeg",
"mpg",
"mpv",
"mxf",
"nsv",
"ogg",
"ogv",
"qt",
"rm",
"rmvb",
"roq",
"svi",
"vob",
"webm",
"wmv",
"yuv"
];
static UrlType getType(url) {
try {
Uri uri = Uri.parse(url);
String extension = p.extension(uri.path).toLowerCase();
if (extension.isEmpty) {
return UrlType.UNKNOWN;
}
extension = extension.split('.').last;
if (_image_types.contains(extension)) {
return UrlType.IMAGE;
} else if (_video_types.contains(extension)) {
return UrlType.VIDEO;
}
} catch (e) {
return UrlType.UNKNOWN;
}
return UrlType.UNKNOWN;
}
}
/// Usage
if(UrlTypeHelper.getType(message) == UrlType.IMAGE) {
/// handle image
}
else if(UrlTypeHelper.getType(message) == UrlType.VIDEO) {
/// handle video
}
My users upload some images to the FileStorage at Backendless.
This is the upload sequence:
Backendless.Files.Android.upload(image1_scaled, Bitmap.CompressFormat.PNG,
100, "profileImage", "images", new AsyncCallback<BackendlessFile>() {
#Override
public void handleResponse(BackendlessFile response) {
fileMapping.profile_url = response.getFileURL();
Backendless.Data.of(FileMapping.class).save(fileMapping,
new AsyncCallback<FileMapping>() {
#Override
public void handleResponse(FileMapping response) {
toast_error("Image stored");
}
#Override
public void handleFault(BackendlessFault fault) {
System.out.println("ERROR" + fault.getCode());
}
});
}
#Override
public void handleFault(BackendlessFault fault) {
}
});
And that works flawlessly. Now I need to fetch back the image with the API to display it.
So I need to make a BackendlessCollection<FileMapping> userFiles = Backendless.Data.of(FileMapping.class) call to receive the URL back from that table. And then supposedly do a httpRequest with the url to get back the byte data.
What I can't work out is what sort of .find method to use? Do I .findById() ? And if so, what ID do I use? The "path", "name" ,"table" etc?
Could anyone show an example fitting my case here, with a table storing the url's and such?
Thanks.
You'd this something like this (showing sync call for simplicity, but make sure to change it to Async on Android):
BackendlessCollection<FileMapping> fileMappings;
fileMappings = Backendless.Data.of( FileMapping.class ).find();
Iterator<FileMapping> iterator = fileMappings.getCurrentPage().iterator();
while( iterator.hasNext() )
{
FileMapping fileMapping = iterator.next();
Log.i( "MyApp", "file URL is " + fileMapping.profile_url );
}
I'm trying to port an existing AJAX app to Flex, and having trouble with the encoding of parameters sent to the backend service.
When trying to perform the action of deleting a contact, the existing app performs a POST, sending the the following: (captured with firebug)
contactRequest.contacts[0].contactId=2c33ddc6012a100096326b40a501ec72
So, I create the following code:
var service:HTTPService;
function initalizeService():void
{
service = new HTTPService();
service.url = "http://someservice";
service.method = 'POST';
}
public function sendReq():void
{
var params:Object = new Object();
params['contactRequest.contacts[0].contactId'] = '2c33ddc6012a100097876b40a501ec72';
service.send(params);
}
In firebug, I see this sent out as follows:
Content-type: application/x-www-form-urlencoded
Content-length: 77
contactRequest%2Econtacts%5B0%5D%2EcontactId=2c33ddc6012a100097876b40a501ec72
Flex is URL encoding the params before sending them, and we're getting an error returned from the server.
How do I disable this encoding, and get the params sent as-is, without the URL encoding?
I feel like the contentType property should be the key - but neither of the defined values work.
Also, I've considered writing a SerializationFilter, but this seems like overkill - is there a simpler way?
Writing a SerializtionFilter seemed to do the trick:
public class MyFilter extends SerializationFilter
{
public function MyFilter()
{
super();
}
override public function serializeBody(operation:AbstractOperation, obj:Object):Object
{
var s:String = "";
var classinfo:Object = ObjectUtil.getClassInfo(obj);
for each (var p:* in classinfo.properties)
{
var val:* = obj[p];
if (val != null)
{
if (s.length > 0)
s += "&";
s += StringUtil.substitute("{0}={1}",p,val);
}
}
return s;
}
}
I'd love to know any alternative solutions that don't involve doing this though!