How to upload an image from a tablet running Windows 8.1 metro application? - microsoft-metro

I need to upload an image to a server, less then 20 lines of code please. and no questions about services. My boss expects it to work like ftp of old days...

I don't think there is a 20 lines solution to your problem.
But check this link out :
http://code.msdn.microsoft.com/Windows-8-SocketsFtp-4fc23b33#content
It contains a full Ftp client that works on Windows 8.1 metro application.
You could use this project as a library in your own project.
If you especially need to upload file, I think you need to use the UploadFileAsync function in FtpClient class
public async Task UploadFileAsync(StorageFile file, string destination)
{
using (var stream = await OpenWriteAsync(destination))
{
//
// A more efficient way, maybe a DataReader can be used here
using (var readStream = await file.OpenReadAsync())
{
var buffer = new byte[512].AsBuffer();
var resultingBuffer = new byte[0];
while (true)
{
IBuffer readBuffer = await readStream.ReadAsync(buffer, 512, InputStreamOptions.Partial);
if (readBuffer.Length == 0) break;
resultingBuffer = resultingBuffer.Concat(readBuffer.ToArray()).ToArray();
}
await stream.WriteAsync(resultingBuffer.AsBuffer());
await stream.FlushAsync();
}
}
}

Related

How to save/share a file in Net. Maui without savefiledialog?

My MauiBlazorApp can create a .pdf file. In what ways can I make this file accessible for the users of windows/android/IOS. A SaveFile Dialog is not yet implemented in Maui. With this path
string SaveToPath = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "hello.pdf");
I can save it on a windows machine and open it (tested).
The path (FileSystem.Current.AppDataDirectory) on a local android device (phone connected to windows maschine via usb) is something like this:
/data/user/0/com.companyname.appname/files/hello.pdf
But later I can't find this folder on my phone. I find this:
/data/com.companyname.appname/cache/ empty folders all the way
Why can't I save a file in .../downloads
How do you import/export data from 'device to device' in Maui? Files seems to be not the way. Email with attechments? Is that possible/better?
You can check the Maui File picker, It provides the method you can pick the file from the device.
public async Task<FileResult> PickAndShow(PickOptions options)
{
try
{
var result = await FilePicker.Default.PickAsync(options);
if (result != null)
{
if (result.FileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) ||
result.FileName.EndsWith("png", StringComparison.OrdinalIgnoreCase))
{
using var stream = await result.OpenReadAsync();
var image = ImageSource.FromStream(() => stream);
}
}
return result;
}
catch (Exception ex)
{
// The user canceled or something went wrong
}
return null;
}
In addition, you can refer to Folder Picker .NET MAUI. This is more detailed.

Can two ASP . NET Core 5.0 web api cause "The content may be already have been read by another component" errpr 400 if they accessed same db be4?

My API was as follows:
[HttpPut("{id}")]
public async Task<ActionResult<HomeContextModel>> EditHomeContext(int id, string title, string context, string subcontext, IFormFile imageFile)
{
HomeContextModel homeContextModel = await _context.HomeContext.Include(x => x.Image).Include(x => x.Button).Include(x => x.Logo).ThenInclude(y => y.Image)
.FirstOrDefaultAsync(m => m.Context_Id == id);
//HomeContextModel homeContextModel = await GetHomeContextModel(id);
if (homeContextModel == null)
{
return BadRequest("Context Id cannot be null");
}
if (imageFile != null)
{
ImageModel imageModel = homeContextModel.Image;
if (imageModel != null)
{
string cloudDomain = "https://privacy-web.conveyor.cloud";
string uploadPath = _webHostEnvironment.WebRootPath + "\\Images\\";
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string filePath = uploadPath + imageFile.FileName;
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await imageFile.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
using (var memoryStream = new MemoryStream())
{
await imageFile.CopyToAsync(memoryStream);
imageModel.Image_Byte = memoryStream.ToArray();
}
imageModel.ImagePath = cloudDomain + "/Images/" + imageFile.FileName;
imageModel.Modify_By = "CMS Admin";
imageModel.Modity_dt = DateTime.Now;
//_context.Update(imageModel);
}
}
homeContextModel.Title = title;
homeContextModel.Context = context;
homeContextModel.SubContext = subcontext;
_context.Entry(homeContextModel).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!HomeContextModelExists(homeContextModel.Context_Id))
{
return NotFound();
}
else
{
throw;
}
}
return Ok("Home Context Edit Successfully");
}
It's an API for the Content Management System (CMS) to change the content of the Homepage using a Flutter webpage that make put request onto this API.
Everything works fine. In the last few days, where I tested and tested again during the development. So before today, I've wrapped up them and submitted to the necessary place (It's a university FYP).
Until now it cause me this error when I was using this to prepare my presentation:
Error 400 failed to read the request form Unexpected end of stream ..."
After all the tested I tried:
Internet solutions
restore the database
repair Microsoft VS 2019 (As this issue was fixed before after I
updated my VS 2019 from 16.8. to the latest 16.11.7)
Use the ASP .NET file which didn't caused this issue before
Then I realized it may be because of I used another older ASP file to accessed the same database before. Does this really cause this matter?
If yes, then now how should I solved it, with the action I already done (listed as above)?
EDIT: Additional description to the situation
The above API I set breakpoint before, on the first line, using Swagger to test it.
It turns out that it didn't go into the API and straightaway return the error 400
REST API can have parameters in at least two ways:
As part of the URL-path
(i.e. /api/resource/parametervalue)
As a query argument
(i.e. /api/resource?parameter=value)
You are passing your parameters as a query instead of a path as indicated in your code. And that is why it is not executing your code and returning 400.

not able to download file with size more than 63kb using UnityWebRequest

i am try to download asset bundle from an url but the request keep on cancelling after downloading 63kb. Can anyone explain to me why this may be happening?
My Code :
public IEnumerator DL()
{
string downloadlink = "https://drive.google.com/file/d/1OGyrB4-MQfo-HVom9ENvV4dn312_wL4Q/view?usp=sharing";
string filepath = Application.persistentDataPath + "/electroplatingNN";
//Download
UnityWebRequest dlreq = new UnityWebRequest(downloadlink);
dlreq.downloadHandler = new DownloadHandlerFile(filepath);
dlreq.timeout = 15;
UnityWebRequestAsyncOperation op = dlreq.SendWebRequest();
while (!op.isDone)
{
//here you can see download progress
Debug.Log(dlreq.downloadedBytes / 1000 + "KB");
yield return null;
}
if (dlreq.isNetworkError || dlreq.isHttpError)
{
Debug.Log(dlreq.error);
}
else
{
Debug.Log("download success");
}
dlreq.Dispose();
yield return null;
}
As already mentioned in the comments the issue is not in the UnityWebrequest but rather Google Drive doesn't simply download your file as you expect.
Instead the data you download is actually only the web page which would allow you to download it. If I simply open your file in a browser I get a page looking like this
where I now could download your file.
There are packages like this or this which implement the necessary stuff for actually download files from Google Drive API in Unity.

How to upload image file in Xamarin forms using rest api . Have issues with large images

I tried and I face a problem when uploading images greater than 570 kb. This issue is in Xamarin Forms for android and PHP rest api. I tested the rest api separately and I have no issues there uploading 2mb files using postman.
Tried various ways also by giving some delay. I am capturing image using cross.media plugin. Then navigating to another page to upload. I wait for sometime and then click the button to upload. I am not able ascertain where the issue is.
System.IO.Stream fileStream = System.IO.File.Open(file, FileMode.Open);
byte[] data = ReadFully(fileStream);
fileStream.Close();
MultipartFormDataContent multi = new MultipartFormDataContent();
ByteArrayContent imageStream = new ByteArrayContent(data);
StringContent SequenceID = new StringContent(osequence);
imageStream.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
imageStream.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = osequence, // "screenshot.jpg", // generate this and send
Name = "avatar",
};
multi.Add(imageStream);
alertLabel.Text = "Uploading Now";
var response = await App.client.PostAsync(url, multi);
string responsestr = response.Content.ReadAsStringAsync().Result;
var retresponse = new retResponse();
bool uploadSuccess = false;
I have made the rest api to send response on error and showing the same in an alert box as below
if (responsestr != "") alertLabel.Text = responsestr.ToString();
else alertLabel.Text = alertLabel.Text + " After Upload Command ";
}
catch (Exception e)
{
}
} // private void upload(MediaFile mediaFile)
The error I get is no file sent
Please ignore the above question. The problem was solved by changing the PHP.ini max upload file size. The file size in the device was around 500 - 700 KB . don't know how it comes to 1.99 and 2 mb when uploaded. Increasing max file size solved it.

Why does sending files from GridFS via MVC4 take so much time?

I want to send images stored in MongoDB using GridFS via a MVC4 Web app to the browser via my LAN environment, but it take ~500ms until the image is sent to the browser.
Google Chrome network inspector says most of the time is spent during "Waiting" while the actual "Receiving" takes ~1ms.
The MongoDB server is in the local network, so what can take so long to send an 10kb image? I use Windows 8 with Visual Studio 2012 and the official mongo-csharp-driver via NuGet.
Here is my code of my "Files" controller which takes an object id and sends the data for this id:
public FileContentResult Files(string id)
{
var database = new MongoClient(MyConnection).GetServer().GetDatabase("MyDB");
var gridFs = new MongoGridFS(database);
var bsonId = new BsonObjectId(id);
var gridInfo = gridFs.FindOneById(bsonId);
var bytes = GridInfoToArray(gridInfo);
return new FileContentResult(bytes, "image/jpeg") { FileDownloadName = gridInfo.Name };
}
private byte[] GridInfoToArray(MongoGridFSFileInfo file)
{
using (var stream = file.OpenRead())
{
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
return bytes;
}
}
Code to display the image in a View:
<img src="#Url.Action("Files", new { id = objectIdOfMyImage) })"/>
How different are the results if you cache your Database and MongoGridFS instances?
// create static fields for _database & _gridFs
var database = _database ??
(_database = new MongoClient(MyConnection).GetServer().GetDatabase("MyDB"));
var gridFs = _gridFs ??
(_gridFs = new MongoGridFS(database));
I'm not sure how much overhead it incurs when you instantiate these, but it wouldn't hurt to move it outside of the method you're trying to optimize.