If I have an element like this in a Windows Store or Windows Phone application:
<Image Source="{Binding UrlToWebServer}" />
the image is cached locally. This is great. But how do I remove all cached images on disc from code?
You just have to set the imagesource to NULL
Something like this:
BitmapImage bitmapImage = myimage.Source as BitmapImage;
bitmapImage.UriSource = null;
myimage.Source = null;
This works for me. Here you can find mor infos handling images (section Image Caching for example).
Hi it´s a little bit late to answer this question but you can use this class to delete the cache of a specific files or all if you want
this is the class helper
class CacheCleanup : IDisposable
{
private DispatcherTimer cleanCacheTimer;
public CacheCleanup(TimeSpan? cleanInterval = null)
{
if (!cleanInterval.HasValue)
cleanInterval = TimeSpan.FromMinutes(0.2);
cleanCacheTimer = new DispatcherTimer();
cleanCacheTimer.Interval = cleanInterval.Value;
cleanCacheTimer.Tick += CleanCacheTimer_Tick;
cleanCacheTimer.Start();
}
private void CleanCacheTimer_Tick(object sender, object e)
{
try
{
StorageFolder localDirectory = ApplicationData.Current.LocalFolder;
string[] tmpCacheDirectories = Directory.GetDirectories(localDirectory.Path + "\\..\\ac\\inetcache");
foreach (string dir in tmpCacheDirectories)
{
string[] tmpCacheFilesPng = Directory.GetFiles(dir, "*.png");
foreach (string file in tmpCacheFilesPng)
{
try
{
File.Delete(file);
Debug.WriteLine("Deleted png: " + file);
}
catch (Exception) { }
}
string[] tmpCacheFilesJpg = Directory.GetFiles(dir, "*.jpg");
foreach (string file in tmpCacheFilesJpg)
{
try
{
File.Delete(file);
Debug.WriteLine("Deleted jpg: " + file);
}
catch (Exception) { }
}
}
}
catch (Exception ex) { Debug.WriteLine("ERROR CLEANING CACHE: " + ex.Message); }
}
public void Dispose()
{
if (cleanCacheTimer != null)
{
cleanCacheTimer.Stop();
cleanCacheTimer = null;
}
}
}
and this is the way how you can call this class in some part of your c# code
CacheCleanup cacheCleanup = new CacheCleanup();
Related
This is the function I used to get the string content from the website ..the problem is when executed first I cannot get the string content (App.Data2 = userprofile.InnerText;) since it skips to the next line (App.savecontent(App.Data2);) so that I get an empty string. If I recall the function I could get the string. Is there any possibility to solve this issue I need the string value first time automatically
This is my Page.cs code :
namespace Project_Future1
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
{
string url = "http://www.astrosage.com/horoscope/daily-";
HtmlWeb.LoadAsync(url + App.Data + "-horoscope.asp", DownLoad);
}
data();
App.loadContent();
change2();
}
public void change2()
{
try
{
Util.LiveTile.UpdateLiveTile(App.Data2);
}
catch (Exception)
{
}
}
public void DownLoad(object sender, HtmlDocumentLoadCompleted e)
{
if (e.Error == null)
{
HtmlDocument doc = e.Document;
if (doc != null)
{
var userprofile = doc.DocumentNode.SelectSingleNode("//div[#class = 'ui-large-content']");
App.Data2 = userprofile.InnerText;
App.savecontent(App.Data2);
}
}
}
private void data()
{
SelectedSign.Text = App.Data;
SSContent.Text = App.Data2;
}
private void Refresh_click(object sender, EventArgs e)
{
SSContent.Text = App.Data2;
}
private void Fb_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/FB.xaml", UriKind.Relative));
}
}
}
this is my App.Xaml.cs File :
public static void savecontent(string save)
{
try
{
if (!string.IsNullOrEmpty(appFileName1))
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
oIsolatedStorage.CreateDirectory(appFolder1);
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(appFolder1 + "\\" + appFileName1, FileMode.OpenOrCreate, oIsolatedStorage));
writeFile.WriteLine(save);
writeFile.Close();
}
}
catch (Exception)
{
throw;
}
}
this is my code to load the content from the storage :
public static void loadContent()
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (oIsolatedStorage.DirectoryExists(appFolder1))
{
IsolatedStorageFileStream fileStream = oIsolatedStorage.OpenFile(appFolder1 + "\\" + appFileName1, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
App.Data2 = reader.ReadLine();
reader.Close();
}
}
}
I have to process an xml against an xslt with result-document that create many xml.
As suggested here:
Catch output stream of xsl result-document
I wrote my personal URI Resolver:
public class CustomOutputURIResolver implements OutputURIResolver{
private File directoryOut;
public CustomOutputURIResolver(File directoryOut) {
super();
this.directoryOut = directoryOut;
}
public void close(Result arg0) throws TransformerException {
}
public Result resolve(String href, String base) throws TransformerException {
FileOutputStream fout = null;
try {
File f = new File(directoryOut.getAbsolutePath() + File.separator + href + File.separator + href + ".xml");
f.getParentFile().mkdirs();
fout = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new StreamResult(fout);
}
}
that get the output directory and then saves here the files.
But then when I tested it in a junit I had some problems in the clean-up phase, when trying to delete the created files and noticed that the FileOutputStream fout is not well handled.
Trying to solve the problem gave me some thoughts:
First I came out with this idea:
public class CustomOutputURIResolver implements OutputURIResolver{
private File directoryOut;
private FileOutputStream fout
public CustomOutputURIResolver(File directoryOut) {
super();
this.directoryOut = directoryOut;
this.fout = null;
}
public void close(Result arg0) throws TransformerException {
try {
if (null != fout) {
fout.flush();
fout.close();
fout = null;
}
} catch (Exception e) {}
}
public Result resolve(String href, String base) throws TransformerException {
try {
if (null != fout) {
fout.flush();
fout.close();
}
} catch (Exception e) {}
fout = null;
try {
File f = new File(directoryOut.getAbsolutePath() + File.separator + href + File.separator + href + ".xml");
f.getParentFile().mkdirs();
fout = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new StreamResult(fout);
}
}
So the fileOutputStream is closed anytime another one is opened.
But:
1) I don't like this solution very much
2) what if this function is called in a multithread process? (I'm not very skilled about Saxon parsing, so i really don't know..)
3) Is there a chance to create and handle one FileOutputStream for each resolve ?
The reason close() takes a Result argument is so that you can identify which stream to close. Why not:
public void close(Result arg0) throws TransformerException {
try {
if (arg0 instanceof StreamResult) {
OutputStream os = ((StreamResult)arg0).getOutputStream();
os.flush();
os.close();
}
} catch (Exception e) {}
}
From Saxon-EE 9.5, xsl:result-document executes in a new thread, so it's very important that the OutputURIResolver should be thread-safe. Because of this change, from 9.5 an OutputURIResolver must implement an additional method getInstance() which makes it easier to manage state: if your newInstance() method actually creates a new instance, then there will be one instance of the OutputURIResolver for each result document being processed, and it can hold the output stream and close it when requested.
I'm developing my first Windows Store App, using MvvmCross framework and I have a problem with images management. In particular I have the following simple ViewModel in my PCL project, and a Store project with a button bound with AddPictureCommand.
public class FirstViewModel : MvxViewModel
{
IMvxPictureChooserTask _pictureChooserTask;
IMvxFileStore _fileStore;
public FirstViewModel(IMvxPictureChooserTask pictureChooserTask, IMvxFileStore fileStore)
{
_pictureChooserTask = pictureChooserTask;
_fileStore = fileStore;
}
private byte[] _pictureBytes;
public byte[] PictureBytes
{
get { return _pictureBytes; }
set
{
if (_pictureBytes == value) return;
_pictureBytes = value;
RaisePropertyChanged(() => PictureBytes);
}
}
public ICommand AddPictureCommand
{
get { return new MvxCommand(() =>
{
_pictureChooserTask.ChoosePictureFromLibrary(400, 95, pictureAvailable, () => { });
}); }
}
private void pictureAvailable(Stream stream)
{
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
PictureBytes = memoryStream.ToArray();
GenerateImagePath();
}
private string GenerateImagePath()
{
if (PictureBytes == null) return null;
var RandomFileName = "Image" + Guid.NewGuid().ToString("N") + ".jpg";
_fileStore.EnsureFolderExists("Images");
var path = _fileStore.PathCombine("Images", RandomFileName);
_fileStore.WriteFile(path, PictureBytes);
return path;
}
}
The problem is that the method _fileStore.EnsureFolderExists("Images");
gives me the an "NotImplementedException" with message: "Need to implement this - doesn't seem obvious from the StorageFolder API".
Has anyone already seen it before?
Thank you
This not implemented exception is documented in the wiki - see https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#File
It should be fairly straightforward to implement these missing methods if they are required. Indeed I know of at least 2 users that have implemented these - but sadly they've not contributed them back.
to implement them, just
fork (copy) the code from https://github.com/MvvmCross/MvvmCross/blob/v3/Plugins/Cirrious/File/Cirrious.MvvmCross.Plugins.File.WindowsStore/MvxWindowsStoreBlockingFileStore.cs
implement the missing methods using the winrt StorageFolder apis
in your Store UI project, don't load the File plugin - so comment out or remove the File bootstrap class.
during setup, register your implementation with ioc using Mvx.RegisterType - e.g.:
protected override void InitializeFirstChance()
{
base.InitializeFirstChance();
Cirrious.CrossCore.Mvx.RegisterType<IMvxFileStore, MyFileStore>();
}
For more on using ioc, see https://github.com/MvvmCross/MvvmCross/wiki/Service-Location-and-Inversion-of-Control
For more on customising the setup sequence, see https://github.com/MvvmCross/MvvmCross/wiki/Customising-using-App-and-Setup
Following Stuart's suggestions I've implemented the following methods for Windows 8 Store App:
public bool FolderExists(string folderPath)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
}
catch (FileNotFoundException)
{
return false;
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in FolderExists - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
return true;
//throw new NotImplementedException("Need to implement this - See EnsureFolderExists");
}
public void EnsureFolderExists(string folderPath)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
}
catch (FileNotFoundException)
{
var localFolder = ToFullPath(string.Empty);
var storageFolder = StorageFolder.GetFolderFromPathAsync(localFolder).Await();
storageFolder.CreateFolderAsync(folderPath).Await();
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in EnsureFolderExists - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
//throw new NotImplementedException("Need to implement this - doesn't seem obvious from the StorageFolder API");
//var folder = StorageFolder.GetFolderFromPathAsync(ToFullPath(folderPath)).Await();
}
The third method we need to implement is DeleteFolder(string folderPath, bool recursive). Unfortunately StorageFolder method "DeleteFolder" doesn't have a "recursive" parameter. So I should implement DeleteFolder ignoring it:
public void DeleteFolder(string folderPath, bool recursive)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
storageFolder.DeleteAsync().Await();
}
catch (FileNotFoundException)
{
//Folder doesn't exist. Nothing to do
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in DeleteFolder - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
//throw new NotImplementedException("Need to implement this - See EnsureFolderExists");
}
or I should check if the folder is empty before to delete it if "recursive" equals false.
Better implementations are welcomed.
I am trying to post some data to our webservice(written in c#) and get the response. The response is in JSON format.
I am using the Blackberry Code Sample which is BlockingSenderDestination Sample. When I request a page it returns with no problem. But when I send my data to our webservice it does not return anything.
The code part that I added is :
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
What am i doing wrong? And what is the alternatives or more efficients way to do Post with Blackberry.
Regards.
Here is my whole code:
class BlockingSenderSample extends MainScreen implements FieldChangeListener {
ButtonField _btnBlock = new ButtonField(Field.FIELD_HCENTER);
private static UiApplication _app = UiApplication.getUiApplication();
private String _result;
public BlockingSenderSample()
{
_btnBlock.setChangeListener(this);
_btnBlock.setLabel("Fetch page");
add(_btnBlock);
}
public void fieldChanged(Field button, int unused)
{
if(button == _btnBlock)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://192.168.1.250/mobileServiceOrjinal.aspx"; //our webservice address
//String uriStr = "http://www.blackberry.com";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("name", URI.create(uriStr));//name for context is name. is it true?
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("ender"),
URI.create(uriStr)
);
}
//Dialog.inform( "1" );
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
if(response != null)
{
BSDResponse(response);
}
}
catch(Exception e)
{
//Dialog.inform( "ex" );
// process the error
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
}
private void BSDResponse(Message msg)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result = new String(data);
}
}
_app.invokeLater(new Runnable() {
public void run() {
_app.pushScreen(new HTTPOutputScreen(_result));
}
});
}
}
..
class HTTPOutputScreen extends MainScreen
{
RichTextField _rtfOutput = new RichTextField();
public HTTPOutputScreen(String message)
{
_rtfOutput.setText("Retrieving data. Please wait...");
add(_rtfOutput);
showContents(message);
}
// After the data has been retrieved, display it
public void showContents(final String result)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
_rtfOutput.setText(result);
}
});
}
}
HttpMessage does not extend ByteMessage so when you do:
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
it throws a ClassCastException. Here's a rough outline of what I would do instead. Note that this is just example code, I'm ignoring exceptions and such.
//Note: the URL will need to be appended with appropriate connection settings
HttpConnection httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
OutputStream out = httpConn.openOutputStream();
out.write(<YOUR DATA HERE>);
out.flush();
out.close();
InputStream in = httpConn.openInputStream();
//Read in the input stream if you want to get the response from the server
if(httpConn.getResponseCode() != HttpConnection.OK)
{
//Do error handling here.
}
i can add images without any problem to my website.with my below code..i am using linq and asp.net with c#....
ImageDatabaseDataContext imdb = new ImageDatabaseDataContext();
Dosyalar ds;
Katilimci kt;
protected void btnEkle_Click(object sender, EventArgs e)
{
if (FileUpload1.FileContent != null)
{
string dosyaAdi = Guid.NewGuid().ToString();
byte[] icerik = FileUpload1.FileBytes;
string dosyaTipi = FileUpload1.PostedFile.ContentType;
try
{
ds = new Dosyalar();
kt = new Katilimci();
kt.AdSoyad = txtAdSoyad.Text;
kt.BolgeMudurlugu = txtBolgeMudurlugu.Text;
kt.Gorevi = txtGorev.Text;
kt.NoktaAd = txtNoktaAd.Text;
kt.NoktaTuru = txtNoktaTuru.Text;
imdb.Katilimcis.InsertOnSubmit(kt);
imdb.SubmitChanges();
int idsi = kt.KID;
ds.DosyaAD = dosyaAdi;
ds.DosyaICERIK = icerik;
ds.DosyaTIP = dosyaTipi;
ds.KID = idsi;
imdb.Dosyalars.InsertOnSubmit(ds);
imdb.SubmitChanges();
}
catch (Exception ex)
{
lblHataci.Text = ex.Message;
}
}
}
here is my question..How do i show my images that i was saving on sql server?on asp.Net website with linq queries?
Thanks for your answer...
you can use the solution to this question as long as you get the contents of the image from the database. it doesnt depend on any linq-to-sql.
Dynamically Rendering asp:Image from BLOB entry in ASP.NET
`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;
}
}
}`
this code solves my question thank you.