Glide with Setter method url image source - android-glide

I would like to set the value of an image attribute in an object class as you would below but using Glide
try {
InputStream stream = new URL("my url").openStream();
Bitmap pictureBitmap = BitmapFactory.decodeStream(stream);
"my model class".setImageBitmap(pictureBitmap);
} catch (IOException e) {
e.printStackTrace();;
}
I guess this is how you fetch the image from the url source using Glide as Bitmap
Glide
.with(getContext())
.load("my url")
.asBitmap()....

You can use SimpleTarget as a parameter on into method. It will load your bitmap and you can put it into your image model after image ready.
Glide
.with(getApplicationContext())
.load(IMAGE_URL)
.asBitmap()
.into(new SimpleTarget<Bitmap>(100,100) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
YourModelClass.setImageBitmap(resource);
}
});

Related

How to get FileUpload working in WASM for Uno Platform

I'm trying to get HTML file upload control working on WASM. So far I've tried to do the following:
[HtmlElement("input")]
public class FilePickerView : FrameworkElement
{
public FilePickerView()
{
// XAML behavior: a non-null background is required on an element to be "visible to pointers".
// Uno reproduces this behavior, so we must set it here even if we're not using the background.
// Not doing this will lead to a `pointer-events: none` CSS style on the control.
Background = new SolidColorBrush(Colors.Transparent);
this.SetHtmlAttribute("type", "file");
}
}
And then in the view:
<wasm:FilePickerView Height="35" Width="300" x:Name="filePicker" HorizontalAlignment="Left" />
I get the control displayed, I can click on it and it displays the name of the file I've selected.
I am pretty lost after this.
I'd like to be able to do two things:
Access file path in code behind.
Send file contents to code behind for processing.
Would appreciate any pointers on this.
I've been through the following pages in the documentation:
(Wasm) Handling custom HTML events - https://qa.website.platform.uno/docs/articles/wasm-custom-events.html
Embedding Existing JavaScript Components Into Uno-WASM - Part 1 - https://qa.website.platform.uno/docs/articles/interop/wasm-javascript-1.html
Embedding Existing JavaScript Components Into Uno-WASM - Part 2 - https://qa.website.platform.uno/docs/articles/interop/wasm-javascript-2.html
Embedding Existing JavaScript Components Into Uno-WASM - Part 3 - https://qa.website.platform.uno/docs/articles/interop/wasm-javascript-3.html
After connecting pieces from the internet, I came up with this method.
However, it only works with files max 500 kb big.
To enable large file upload I had to upgrade wasm target to .net 5 and use developer versions (2.0.0-dev.167) of Uno.Wasm.Bootstrap and Uno.WasmBootstrap.DevServer (how to upgrade target is described here).
In this code I enabled upload of only .wav audio files
private async void uploadBtn_Click(object sender, RoutedEventArgs e)
{
FileSelectedEvent -=OnFileUploadedEvent;
FileSelectedEvent += OnFileUploadedEvent;
WebAssemblyRuntime.InvokeJS(#"
var input = document.createElement('input');
input.type = 'file';
input.accept = '.wav';
input.onchange = e => {
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = readerEvent => {
//this is the binary uploaded content
var content = readerEvent.target.result;
//invoke C# method to get audio binary data
var selectFile = Module.mono_bind_static_method(" + "\"[MyApp.Wasm] MyApp.Shared.MyPage:SelectFile\""+#");
selectFile(content);
};
};
input.click(); "
);
}
public static void SelectFile(string fileAsDataUrl) => FileSelectedEvent?.Invoke(null, new FileSelectedEventHandlerArgs(fileAsDataUrl));
private void OnFileUploadedEvent(object sender, FileSelectedEventHandlerArgs e)
{
FileSelectedEvent -= OnFileUploadedEvent;
var base64Data = Regex.Match(e.FileAsDataUrl, #"data:audio/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data); //this is the data I want
Console.Out.WriteLine("I got binary data of uploaded file");
}
private static event FileSelectedEventHandler FileSelectedEvent;
private delegate void FileSelectedEventHandler(object sender, FileSelectedEventHandlerArgs args);
private class FileSelectedEventHandlerArgs
{
public string FileAsDataUrl { get; }
public FileSelectedEventHandlerArgs(string fileAsDataUrl) => FileAsDataUrl = fileAsDataUrl;
}
Also I was not able to run it with SQLite at the same time. Sadly, I still haven't figured out why.
Sources:
https://github.com/unoplatform/uno/issues/508
https://github.com/unoplatform/uno/issues/3525
https://platform.uno/blog/uno-platform-3-2-net-5-c-9-support-and-net-5-webassembly-aot-support/
EDIT: Appareantly SQLite for .NET 5/6 is still work in progress and there are some packages that need changes.

how to convert Bitmap to Imagesource Xamarin?

I need to convert bitmap to Imagesource. I have searched online but I can only find examples the other way around.
Do you please have any examples?
how to convert Bitmap to Imagesource Xamarin
You coudl convert the bitmap to stream first on the native platform, then get the imageSource from the stream. You could use DependencyService to achieve the function and call the method in the shared project.
Check the code:
Create an interface in the shared project.
public interface IGetFileStream
{
MemoryStream getStream();
}
Implement the interface in the required platform projects.
[assembly: Dependency(typeof(DroidGetStreamImplement))]
namespace App19F_9.Droid
{
public class DroidGetStreamImplement : IGetFileStream
{
public MemoryStream getStream()
{
var bitmap = ...;
var stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
bitmap.Recycle();
return stream;
}
}
}
Resolve the platform implementations from shared code.
public partial class Page5 : ContentPage
{
public Page5()
{
InitializeComponent();
var stream = DependencyService.Get<IGetFileStream>().getStream();
image.Source = ImageSource.FromStream(stream);
}
}

How to reload apache commons configurations2 properties

can anyone guide me on how to perform a reload of an apache commons configuration2 properties. I'm unable to find any implementation of this anywhere. The apache docs are a bit too abstract. This is what I have so far but it's not working.
CombinedConfiguration cc = new CombinedConfiguration();
Parameters params = new Parameters();
File configFile = new File("config.properties");
File emsFile = new File("anotherconfig.properties");
ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> configBuilder =
new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.fileBased()
.setFile(configFile));
PeriodicReloadingTrigger reloadTrg = new PeriodicReloadingTrigger(configBuilder.getReloadingController(), null, 5, TimeUnit.SECONDS);
reloadTrg.start();
cc.addConfiguration(configBuilder.getConfiguration());
FileBasedConfigurationBuilder<FileBasedConfiguration> emsBuilder =
new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.properties()
.setFile(emsFile));
cc.addConfiguration(emsBuilder.getConfiguration());
DataSource ds = EmsDataSource.getInstance().getDatasource(this);
BasicConfigurationBuilder<DatabaseConfiguration> dbBuilder =
new BasicConfigurationBuilder<DatabaseConfiguration>(DatabaseConfiguration.class);
dbBuilder.configure(
params.database()
.setDataSource(ds)
.setTable("EMS_CONFIG")
.setKeyColumn("KEY")
.setValueColumn("VALUE")
);
cc.addConfiguration(dbBuilder.getConfiguration());
The configuration obtained from a builder is not updated automatically. You need to get the configuration from the builder every time you read it.
From Automatic Reloading of Configuration Sources:
One important point to keep in mind when using this approach to reloading is that reloads are only functional if the builder is used as central component for accessing configuration data. The configuration instance obtained from the builder will not change automagically! So if an application fetches a configuration object from the builder at startup and then uses it throughout its life time, changes on the external configuration file become never visible. The correct approach is to keep a reference to the builder centrally and obtain the configuration from there every time configuration data is needed.
use following code:
#Component
public class ApplicationProperties {
private PropertiesConfiguration configuration;
#PostConstruct
private void init() {
try {
String filePath = PropertiesConstants.PROPERTIES_FILE_PATH;
System.out.println("Loading the properties file: " + filePath);
configuration = new PropertiesConfiguration(filePath);
//Create new FileChangedReloadingStrategy to reload the properties file based on the given time interval
FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy();
fileChangedReloadingStrategy.setRefreshDelay(PropertiesConstants.REFRESH_DELAY);
configuration.setReloadingStrategy(fileChangedReloadingStrategy);
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
public String getProperty(String key) {
return (String) configuration.getProperty(key);
}
public void setProperty(String key, Object value) {
configuration.setProperty(key, value);
}
public void save() {
try {
configuration.save();
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
}

tool/script to visit all pages in an ASP.NET project?

Does anybody know of a tool, script, package, whatever that I can use to visit all pages in an ASP.NET Webforms web application project? (we aren't using any MVC functionality)
Preferably, I would like to be able to generate a list of URLs to hit, edit the list so I can add some query string params, hit all the pages in the list, and collect HTTP response codes: (200, 404, 500, 301, whatever).
Design time
Instead of using string literals for URLs in your application, define Url() methods in each page class like this:
public static string Url() { get { return "~/this_page.aspx"; } }
public static string Url(int ID) { get { return "~/this_page.aspx?id=" + ID; } }
Or list all URLs in a static class
public static class URL {
public static string Login() { get { return "~/login.aspx"; } }
public static string DisplayRecord(int recordID)
{ get { return "~/display.aspx?id=" + recordID; } }
Runtime
Use a web testing framework to crawl all links and edit the result. I blogged about one possible solution using Selenium.
I made a WinForms application that gets the pages that can be accessed from the .csproject and can open them by clicking a button.
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
namespace OpenAllPages
{
public partial class Form1 : Form
{
public static IList<string> Pages;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string xmlstring = ReadXml("TaskManager.csproj");
Pages = ParseAllPages(xmlstring);
pagesListBox.DataSource = Pages;
}
private string ReadXml(string location)
{
try
{
var myFile = new StreamReader(location);
string myString = myFile.ReadToEnd();
myFile.Close();
return myString;
}
catch (Exception e)
{
MessageBox.Show(String.Format("An error occurred: '{0}'", e.Message));
}
return null;
}
private IList<string> ParseAllPages(string xmlstring)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlstring);
XPathNavigator nav = xmlDoc.DocumentElement.CreateNavigator();
XmlNamespaceManager manager = new XmlNamespaceManager(nav.NameTable);
manager.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");
var elements = nav.Select("x:ItemGroup/x:Content", manager);
var pageList = new List<string>();
while (elements.MoveNext())
{
var page = elements.Current.GetAttribute("Include", "");
if (page.EndsWith(".aspx"))
pageList.Add(page);
}
return pageList as IList<string>;
}
private string AddPagePrefix(string page)
{
return "http://localhost:8080/" + page;
}
private void openAllButton_Click(object sender, EventArgs e)
{
foreach (string page in Pages)
System.Diagnostics.Process.Start("chrome.exe", AddPagePrefix(page));
}
}
}
Here is a link to the code
You need to place the project file which contains the pages you want to open in the OpenAllPages project and set it's Copy to Output property to "Copy if newer".
I Form1_Load change TaskManager.csproj to the name of your project file.
And in:
System.Diagnostics.Process.Start("chrome.exe", AddPagePrefix(page));
rename parameter to the executable of the browser you are using.

Dynamically Rendering asp:Image from BLOB entry in ASP.NET

What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site.
I have done this by using
Response.Clear();
Response.ContentType = "image/pjpeg";
Response.BinaryWrite(imageConents);
Response.End();
but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible?
Add a 'Generic Handler' to your web project, name it something like Image.ashx. Implement it like this:
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
using(Image image = GetImage(context.Request.QueryString["ID"]))
{
context.Response.ContentType = "image/jpeg";
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
public bool IsReusable
{
get
{
return true;
}
}
}
Now just implement the GetImage method to load the image with the given ID, and you can use
<asp:Image runat="server" ImageUrl="~/Image.ashx?ID=myImageId" />
to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved).
You can BASE64 encode the content of the image directly into the SRC attribute, however, I believe only Firefox will parse this back into an image.
What I typically do is a create a very lightweight HTTPHandler to serve the images:
using System;
using System.Web;
namespace Example
{
public class GetImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString("id") != null)
{
Blob = GetBlobFromDataBase(id);
context.Response.Clear();
context.Response.ContentType = "image/pjpeg";
context.Response.BinaryWrite(Blob);
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You can reference this directly in your img tag:
<img src="GetImage.ashx?id=111"/>
Or, you could even create a server control that does it for you:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Example.WebControl
{
[ToolboxData("<{0}:DatabaseImage runat=server></{0}:DatabaseImage>")]
public class DatabaseImage : Control
{
public int DatabaseId
{
get
{
if (ViewState["DatabaseId" + this.ID] == null)
return 0;
else
return ViewState["DataBaseId"];
}
set
{
ViewState["DatabaseId" + this.ID] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write("<img src='getImage.ashx?id=" + this.DatabaseId + "'/>");
base.RenderContents(output);
}
}
}
This could be used like
<cc:DatabaseImage id="db1" DatabaseId="123" runat="server/>
And of course, you could set the databaseId in the codebehind as needed.
You don't want to be serving blobs from a database without implementing client side caching.
You will need to handle the following headers to support client side caching:
ETag
Expires
Last-Modified
If-Match
If-None-Match
If-Modified-Since
If-Unmodified-Since
Unless-Modified-Since
For an http handler that does this, check out:
http://code.google.com/p/talifun-web/wiki/StaticFileHandler
It has a nice helper to serve the content. It should be easy to pass in database stream to it. It also does server side caching which should help alleviate some of the pressure on the database.
If you ever decide to serve streaming content from the database, pdfs or large files the handler also supports 206 partial requests.
It also supports gzip and deflate compression.
These file types will benefit from further compression:
css, js, htm, html, swf, xml, xslt, txt
doc, xls, ppt
There are some file types that will not benefit from further compression:
pdf (causes problems with certain versions in IE and it is usually well compressed)
png, jpg, jpeg, gif, ico
wav, mp3, m4a, aac (wav is often compressed)
3gp, 3g2, asf, avi, dv, flv, mov, mp4, mpg, mpeg, wmv
zip, rar, 7z, arj
Using ASP.Net with MVC this is pretty forward easy. You code a controller with a method like this:
public FileContentResult Image(int id)
{
//Get data from database. The Image BLOB is return like byte[]
SomeLogic ItemsDB= new SomeLogic("[ImageId]=" + id.ToString());
FileContentResult MyImage = null;
if (ItemsDB.Count > 0)
{
MyImage= new FileContentResult(ItemsDB.Image, "image/jpg");
}
return MyImage;
}
In your ASP.NET Web View or in this example, in your ASP.NET Web Form you can fill an Image Control with the URL to your method like this:
this.imgExample.ImageUrl = "~/Items/Image/" + MyItem.Id.ToString();
this.imgExample.Height = new Unit(120);
this.imgExample.Width = new Unit(120);
Voilá. Not HttpModules hassle was needed.
We actually just released some classes that help with exactly this kind of thing:
http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449
Specifically, check out the DatabaseImage sample.
Add the code to a handler to return the image bytes with the appropriate mime-type. Then you can just add the url to your handler like it is an image. For example:
<img src="myhandler.ashx?imageid=5">
Make sense?

Resources