Hy.
I do an application in WP7 which is connet a FTP server. I would like to upload a photo(with photochoosertask).
I wrote a PhotoChooserTask() which I could choose a photo. The program save the photo name(samplephoto01.jpg) and the photo route.
And I wrote a code which send command to FTP server:
public static void Execute(String msg)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
Byte[] cmd = Encoding.UTF8.GetBytes((msg + "\r\n").ToCharArray());
socketEventArg.SetBuffer(cmd, 0, cmd.Length);
socket.SendAsync(socketEventArg);
}
This code i can chose the photo:
public void SelectAndUpLoad()
{
PhotoChooserTask p = new PhotoChooserTask();
p.Completed += new EventHandler<PhotoResult>(pt_Completed);
p.ShowCamera = true;
p.Show();
}
void pt_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage img = new BitmapImage();
img.SetSource(e.ChosenPhoto);
MediaLibrary library = new MediaLibrary();
string PhotoPath = e.OriginalFileName;
// MessageBox.Show(PhotoPath);
for (int i = 0; i < library.Pictures.Count; i++)
{
Stream s = library.Pictures[i].GetImage();
if (s.Length == e.ChosenPhoto.Length)
{
string filename = library.Pictures[i].Name;
MessageBoxResult m = MessageBox.Show(filename, "Upload?", MessageBoxButton.OKCancel);
if (m == MessageBoxResult.OK)
{
Ftp.UploadFile(PhotoPath);
}
else
{
return;
}
break;
}
}
}
}
And this is the code whic i would like to upload the file:
public static void UploadFile(string file)
{
FileStream stream = new FileStream(file, FileMode.Open);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Execute("STRO " + file);
stream.Seek(0, SeekOrigin.Begin);
stream.Close();
}
But when i use the UploadFile(); method the program answer this:
MethodAccessException was unhandled
This code:
.
.
Ftp.UploadFile(PhotoPath);
}
else
{ //MethodAccessException
return;
}
break;
}
What was the wrong? Thank you!
I rewrote this code with IsolatedStorage to this:
for (int i = 0; i < library.Pictures.Count; i++)
{
Stream s = library.Pictures[i].GetImage();
if (s.Length == e.ChosenPhoto.Length)
{
string filename = library.Pictures[i].Name;
MessageBoxResult m = MessageBox.Show(filename, "Upload?", MessageBoxButton.OKCancel);
if (m == MessageBoxResult.OK)
{
IsolatedStorageFile iss = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fs = iss.OpenFile(PhotoPath, FileMode.Open);
Ftp.UploadFile(fs, filename);
fs.Close();
}
else
{
return;
}
break;
}
}
And the UploadFile() method:
public static void UploadFile(IsolatedStorageFileStream file, string RemoteFile)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
int bytes;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Execute("STRO " + RemoteFile);
file.Seek(0, SeekOrigin.Begin);
while ((bytes = file.Read(buffer, 0, buffer.Length)) > 0)
{
socketEventArg.SetBuffer(buffer, bytes, 0);
socket.SendAsync(socketEventArg);
}
}
But i get an exception in this source:
IsolatedStorageFileStream fs = iss.OpenFile(PhotoPath, FileMode.Open);
The exception is: IsolatedStorageException was unhadnled.
What is wrong?
I think your problem lies in the line:
FileStream stream = new FileStream(file, FileMode.Open);
You can't open files this way on WP7. To get a stream to a file, you can either open it from the Isolated Storage (given that the file is stored there), or use the stream provided by a built-in method.
In your case, you have the stream with the property e.ChosenPhoto. Why don't you use it directly?
public static void UploadFile(Stream stream, string file)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Execute("STRO " + file);
stream.Seek(0, SeekOrigin.Begin);
stream.Close();
}
Then call UploadFile using e.ChosenPhoto as the first argument.
Related
This is driving me crazy. I wrote a code quite a while ago that was working, and opened it again and it happens that I am not able to transfer my assets from the mobile to the wearable device.
public Bitmap loadBitmapFromAsset(Asset asset) {
if (asset == null) {
throw new IllegalArgumentException("Asset must be non-null");
}
// convert asset into a file descriptor and block until it's ready
Log.d(TAG, "api client" + mApiClient);
DataApi.GetFdForAssetResult result = Wearable.DataApi.getFdForAsset(mApiClient, asset).await();
if (result == null) {
Log.w(TAG, "getFdForAsset returned null");
return null;
}
if (result.getStatus().isSuccess()) {
Log.d(TAG, "success");
} else {
Log.d(TAG, result.getStatus().getStatusCode() + ":" + result.getStatus().getStatusMessage());
}
InputStream assetInputStream = result.getInputStream();
if (assetInputStream == null) {
Log.w(TAG, "Requested an unknown Asset.");
return null;
}
// decode the stream into a bitmap
return BitmapFactory.decodeStream(assetInputStream);
}
And this is the code from which I call the loadBitmapFrom Asset method.
DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
ArrayList<DataMap> dataMaps = dataMap.getDataMapArrayList("dataMaps");
ArrayList<String> names = new ArrayList<>();
ArrayList<String> permalinks = new ArrayList<>();
ArrayList<Asset> images = new ArrayList<>();
for (int i = 0 ; i < dataMaps.size() ; i++) {
Log.d(TAG, dataMaps.get(i).getString("name"));
names.add(dataMaps.get(i).getString("name"));
permalinks.add(dataMaps.get(i).getString("permalink"));
images.add(dataMaps.get(i).getAsset("image"));
}
editor.putInt("my_selection_size", names.size());
for (int i=0; i <names.size() ; i++) {
editor.putString("my_selection_name_" + i, names.get(i));
editor.putString("my_selection_permalink_" + i, permalinks.get(i));
Log.d(TAG, "asset number " + i + " " + images.get(i));
Bitmap bitmap = loadBitmapFromAsset(images.get(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
editor.putString("my_selection_image_" + i, encoded);
}
And on the mobile side :
private void sendData(PutDataMapRequest dataMap) {
PutDataRequest request = dataMap.asPutDataRequest();
request.setUrgent();
com.google.android.gms.common.api.PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mApiClient, request);
pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(DataApi.DataItemResult dataItemResult) {
com.orange.radio.horizon.tools.Log.d(TAG, "api client : " + mApiClient);
if (dataItemResult.getStatus().isSuccess()) {
com.orange.radio.horizon.tools.Log.d(TAG, "message successfully sent");
} else if (dataItemResult.getStatus().isInterrupted()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (interrupted)");
} else if (dataItemResult.getStatus().isCanceled()) {
com.orange.radio.horizon.tools.Log.e(TAG, "couldn't send data to watch (canceled)");
}
}
});
Log.d(TAG, "Sending data to android wear");
}
class ConfigTask extends AsyncTask<String, Void, String> {
ArrayList<WatchData> mitems;
int mType;
public ConfigTask(ArrayList<WatchData> items, int type)
{
mitems = items;
mType = type;
}
protected String doInBackground(String... str)
{
DataMap dataMap;
ArrayList<DataMap> dataMaps = new ArrayList<>();
Bitmap bitmap = null;
for (int i = 0 ; i < mitems.size() ; i++) {
dataMap = new DataMap();
URL url = null;
try {
url = new URL(mitems.get(i).mUrlSmallLogo);
Log.d(TAG, "url : " + url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
Asset asset = createAssetFromBitmap(bitmap);
dataMap.putAsset("image", asset);
dataMap.putString("name", mitems.get(i).mName);
dataMap.putString("permalink", mitems.get(i).mPermalink);
dataMaps.add(dataMap);
}
PutDataMapRequest request = null;
switch (mType) {
case 0 :
request = PutDataMapRequest.create(SELECTION_PATH);
break;
case 1 :
request = PutDataMapRequest.create(RADIOS_PATH);
break;
case 2 :
request = PutDataMapRequest.create(PODCASTS_PATH);
break;
}
request.getDataMap().putDataMapArrayList("dataMaps", dataMaps);
request.getDataMap().putString("", "" + System.currentTimeMillis()); //random data to refresh
Log.d(TAG, "last bitmap : " + bitmap);
Log.d(TAG, "===============================SENDING THE DATAMAP ARRAYLIST==================================");
sendData(request);
return "h";
}
protected void onPostExecute(String name)
{
}
}
When executing that code, I see the following error happening :
02-02 14:47:59.586 7585-7601/? D/WearMessageListenerService﹕ 4005:ASSET_UNAVAILABLE
I saw that related thread Why does Wearable.DataApi.getFdForAsset produce a result with status 4005 (Asset Unavailable)? but it didn't really help me
I recently had the same problem... I solved it by updating the Google play service, and adding the same signing configuration to both the app and the wearable module. If it doesn't work on the first build go to "invalidate caches / restart" in files and it should work.
I am trying to stream video file . when i open the same video file in another tab of browser , i get the message "file is being used by another process" . if I use FileShare.ReadWrite in file.open method then error goes away but video doesn't play in browser . can someone pl. help .
public HttpResponseMessage Get([string id)
{
var path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["path"] + "/" + id);
var video = new VideoStream(path);
HttpResponseMessage response = Request.CreateResponse();
var contentType = ConfigurationManager.AppSettings[Path.GetExtension(id)];
response.Content = new PushStreamContent(video.WriteToStream, new MediaTypeHeaderValue(contentType));
return response;
}
public class VideoStream
{
private readonly string _filename;
public VideoStream(string filename)
{
_filename = filename;
}
public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
try
{
var buffer = new byte[65536];
using (var video = File.Open(_filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
var length = (int) video.Length;
var bytesRead = 1;
while (length > 0 && bytesRead > 0)
{
bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
await outputStream.WriteAsync(buffer, 0, bytesRead);
length -= bytesRead;
video.Flush();
}
}
}
catch (HttpException ex)
{
return;
}
finally
{
// outputStream.Close();
// outputStream.Flush();
}
}
}
You should use:
File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read);
Assuming the file lock comes from the server. Is that the case, or is it a client side thing?
String url1 = "http://localhost/Images/Map.png";
I want to load images"Map.png" from this link then saving to isolated storage.
public void GetImages()
{
WebClient m_webClient = new WebClient();
Uri m_uri = new Uri("http://localhost/Images/Map.png");
m_webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
m_webClient.OpenReadAsync(m_uri);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
int count;
Stream stream = e.Result;
byte[] buffer = new byte[1024];
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
// isf.Remove();
//if (!isf.FileExists("map"))
//{
using (System.IO.IsolatedStorage.IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("map", FileMode.Create, isf))
{
count = 0;
while (0 < (count = stream.Read(buffer, 0, buffer.Length)))
{
isfs.Write(buffer, 0, count);
}
stream.Close();
isfs.Close();
}
}
This can be usefull for windows 8 phone
http://code.msdn.microsoft.com/wpapps/CSWP8ImageFromIsolatedStora-8dcf8411
I am trying to read a text file from IsolatedStorage and check it contains a string. If not, the string is added to the end of the file. But When I am trying to write the string into file I got an error: "Operation not permitted on IsolatedStorageFileStream.". My code shown below. How can I overcome this problem?
public void AddToDownloadList()
{
IsolatedStorageFile downloadFile=IsolatedStorageFile.GetUserStoreForApplication();
try
{
string downloads = string.Empty;
if (!downloadFile.DirectoryExists("DownloadedFiles"))
downloadFile.CreateDirectory( "DownloadedFiles" );
if(downloadFile.FileExists("DownloadedFiles\\DownloadList.txt"))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile("DownloadedFiles\\DownloadList.txt",FileMode.Open, FileAccess.Read );
using ( StreamReader reader = new StreamReader( downloadStream ) )
{
downloads = reader.ReadToEnd();
reader.Close();
}
downloadFile.DeleteFile( "DownloadedFiles\\DownloadList.txt" );
}
downloadFile.CreateFile( "DownloadedFiles\\DownloadList.txt" );
string currentFile = FileName;
if ( !downloads.Contains( currentFile ) )
{
downloads += currentFile;
using ( StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream( "DownloadedFiles\\DownloadList.txt", FileMode.Create, FileAccess.Write, downloadFile ) ) )
{
writeFile.Write( currentFile + "," );
writeFile.Close();
}
}
}
catch ( Exception ex )
{
string message = ex.Message;
}
}
I think the problem you were having has to do with the line where you create the StreamWriter by newing up the IsolatedStorageFileStream - when you already should have the right one from the return of the downloadFile.CreateFile() call.
Try this code, I think it does what you want to do:
public static void AddToDownloadList()
{
try
{
AddToDownloadList("DownloadedFiles", "this file name", "DownloadedFiles\\DownloadList.txt");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
}
}
public static void AddToDownloadList(string directory, string fileName, string filePath)
{
string downloads = string.Empty;
using (IsolatedStorageFile downloadFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!downloadFile.DirectoryExists(directory))
downloadFile.CreateDirectory(directory);
if (downloadFile.FileExists(filePath))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile(filePath, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(downloadStream))
{
downloads = reader.ReadToEnd();
reader.Close();
}
}
string currentFile = fileName;
if (!downloads.Contains(currentFile))
{
downloadFile.DeleteFile(filePath);
using (IsolatedStorageFileStream stream = downloadFile.CreateFile(filePath))
{
downloads += currentFile;
using (StreamWriter writeFile = new StreamWriter(stream))
{
writeFile.Write(currentFile + ",");
writeFile.Close();
}
}
}
}
}
I need to download jpeg image and show it in my midlet.
But when I try to run this code, image on screen is broken.
What is wrong?
public void startApp() {
HttpConnection conn = null;
InputStream is = null;
try {
conn = (HttpConnection) Connector.open("http://av.li.ru/227/2374227_8677578.jpg", Connector.READ, false);
conn.setRequestMethod( HttpConnection.GET);
int rc = conn.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new Exception("ResponseCode = " + rc);
}
is = conn.openDataInputStream();
byte []b = new byte[(int) conn.getLength()];
is.read(b);
Image img = Image.createImage(b, 0, b.length);
Form f = new Form("test");
f.append(img);
Display.getDisplay(this).setCurrent(f);
} catch (Exception e) {
}
}
Thanks