File size limit in Windows Phone application using C# - c#

I am new in Windows Phone application. In my application, when uploading files it is required to add file size limit not exceeding 50kb.
Code:
public sealed class OpenFileDialog
{
public string Filter { get; set; }
internal static object ShowDialog()
{
throw new NotImplementedException();
}
public static object DialogResult { get; set; }
public static string FileName { get; set; }
}
if (OpenFileDialog.ShowDialog() == System.Windows.Controls.DialogResult.OK)
{
FileStream fs = File.OpenRead(OpenFileDialog.FileName);
if (fs.Length > 51200)
{
MessageBox.Show("Image size must not exceed 50kb.");
return;
}
System.Windows.Controls.Image myImage = new System.Windows.Controls.Image();
myImage.Source = bmp;
}
but it show error,
Error:
namespace dialogresult doesn't exist in the namespace system.windows.controls(missing a assembly reference)
Anybody help me to solve this error?

You're attempting to use an enumeration that is part of the System.Windows.Forms namespace, and no such open file dialog exists in the Windows Phone 8 library. Without knowing more about your file access scenario, I will point out that your options would include:
Application Isolated Storage
Known Folders (WP 8.1 only including music, videos, photos, and SD card storage)
I'll point you to this general guide to accessing files programmatically which may take you to where you need to be specifically, but I should point out that since the most commonly accessible files on a phone device are rarely 50kb or less in size, we likely need more information about your use case.

Related

How to create a button which takes a picture

I'm writing a cross-platform (iOS and Android) app in C# using Xamarin on Visual Studio Community 2022. I have implemented a camera preview on the app using the code found at this website :
https://www.c-sharpcorner.com/article/creating-a-custom-camera-view-basic-concept-create-half-screen-camera-in-xamari/
The code on the website is for iOS, but there is a link at the bottom to download a folder which contains the code for Android as well. My app now displays a camera preview, but there is no way to take a picture with this. I therefore want to create a button which takes a picture without having to open the camera app. I'd also like the resulting photo to not be saved in the photos of the phone. I have looked but have found no way of doing exactly what I want, and therefore I don't know where to get started. If the answer could give as many details as possible about how to do this for both platforms it would be appreciated. Also, would the resulting photo be of the type FileResult? I have previously worked with the mediapicker in Xamarin which returns the type FileResult, but have come to realize that there are limitations within the mediapicker and I therefore can't work with it.
Thanks a lot :)
You can try MediaPicker to capture picture.And get the filepath in photo.FullPath.
You can refer to the link below to get more details:
https://learn.microsoft.com/en-us/xamarin/essentials/media-picker?tabs=ios
edit:
private void cameraView_MediaCaptured(object sender, Xamarin.CommunityToolkit.UI.Views.MediaCapturedEventArgs e)
{
byte[] image = e.ImageData;
DependencyService.Get<ISaveService>().wirteFile("pic.jpg", image);
}
public interface ISaveService
{
void SaveFile(string fileName, byte[] data);
}
Android:
[assembly: Xamarin.Forms.Dependency(typeof(SaveService))]
namespace cameraviewDemo.Droid
{
public class SaveService: ISaveService
{
void ISaveService.SaveFile(string fileName, byte[] data)
{
string picPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryPictures);
string filePath = Path.Combine(picPath, fileName);
File.WriteAllBytes(filePath, data);
}
}
}
iOS:
[assembly: Xamarin.Forms.Dependency(typeof(SaveService))]
namespace cameraviewDemo.iOS
{
class SaveService: ISaveService
{
void ISaveService.SaveFile(string fileName, byte[] data)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(documents, fileName);
File.WriteAllBytes(filename, data);
}
}
}

How to get thumbnails from a file

I have build a winform application which connects a technical drawing application (CAD - SolidEdge) and an ERP-system. This is working fine but I can't get the right thumbnails in the bomstructure.
When I click on a file in Windows (Windows 10) I see a nice preview image. How can I extract this image to my application?
I had found a similar question and solution (Extract thumbnail for any file in Windows) but this is won't work anymore (because of Windows 10 updates I guess).
Also this one (C# get thumbnail from file via windows api) doesn't work and gives: Example wrong thumbnail and Example wrong thumbnail.
Have you guys any idea how to solve this? Thanks!!
There are different types of thumbnails that can be retrieved from Windows.
Picture
Song Album Art
Document Icon
Folder
File Group
Single Item
Microsoft has a nice sample project called FileThumbnails that lets you play with each type. This project was updated for Windows10 and VS 2019 in March 2020. Although it's a universal windows project instead of winforms.
After playing with the different modes I found the one you are after for Solid Edge files is #6.
internal class FileExtensions
{
public static readonly string[] SEfiles = new string[] { ".dft", ".par", ".asm" };
}
FileOpenPicker openPicker = new FileOpenPicker();
foreach (string extension in FileExtensions.SEfiles)
{
openPicker.FileTypeFilter.Add(extension);
}
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
const ThumbnailMode thumbnailMode = ThumbnailMode.SingleItem;
bool fastThumbnail = FastThumbnailCheckBox.IsChecked.Value;
ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale;
if (fastThumbnail)
{
thumbnailOptions |= ThumbnailOptions.ReturnOnlyIfCached;
}
using (StorageItemThumbnail thumbnail = await file.GetScaledImageAsThumbnailAsync(thumbnailMode, size, thumbnailOptions))
{
if (thumbnail != null)
{
MainPage.DisplayResult(ThumbnailImage, OutputTextBlock, thumbnailMode.ToString(), size, file, thumbnail, false);
}
else
{
rootPage.NotifyUser(Errors.NoThumbnail, NotifyType.StatusMessage);
}
}
}
public static void DisplayResult(Image image, TextBlock textBlock, string thumbnailModeName, uint size, IStorageItem item, StorageItemThumbnail thumbnail, bool isGroup)
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(thumbnail);
image.Source = bitmapImage;
textBlock.Text = String.Format("ThumbnailMode.{0}\n"
+ "{1} used: {2}\n"
+ "Requested size: {3}\n"
+ "Returned size: {4}x{5}",
thumbnailModeName,
isGroup ? "Group" : item.IsOfType(StorageItemTypes.File) ? "File" : "Folder",
item.Name,
size,
thumbnail.OriginalWidth,
thumbnail.OriginalHeight);
}
Result Example:

Open custom files with own C# application

I'm creating a media player.
So far I can open a file type with my C# application by double clicking on the file. But I want to open multiple files by selecting them and opening them at once..
My code goes as follows:
App.xmal.cs
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args != null && e.Args.Length > 0)
{
this.Properties["ArbitraryArgName"] = e.Args[0];
}
base.OnStartup(e);
}
MainWindow.xmal.cs
if (Application.Current.Properties["ArbitraryArgName"] != null)
{
string fname = Application.Current.Properties["ArbitraryArgName"].ToString();
if (fname.EndsWith(".mp3") || fname.EndsWith(".wma") || fname.EndsWith(".wav") || fname.EndsWith(".mpg") ||
fname.EndsWith(".mpeg") || fname.EndsWith(".mp4") || fname.EndsWith(".wmv") )
{
doubleclicktrack(fname);
}
else
{
this.Close();
}
}
This code works fine with one file, but how to change this in order to open multiple files at once by selecting multiple files and opening them at once (by pressing enter key).
You will have to look into developing shell extensions in order to achieve what you want. Just by using the registry to associate file types with your app, you are limited to passing just one file per command, which will end up opening your app once per file (which you have confirmed).
I guess you could also implement your app to allow only one instance running globally. That way, whenever a command comes in to open one more file, you could for example add it to a playlist or something.
Note that shell extensions have to be written in C++, Microsoft strongly advises to avoid managed code for this purpose.
You can find the documentation starting point here: https://msdn.microsoft.com/en-us/library/windows/desktop/bb776778(v=vs.85).aspx
FileOpenPicker can do that (Code for UWP or Windows 8.1 desktop, with Windows 8.1 phone it's a bit trickier):
private static readonly string[] FileTypes = {
"aac", "adt", "adts", "mp3", "m3a", "m4a", "mpr", "3gp", "3g2",
"flac", "wav", "wma" };
...........
FileOpenPicker picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
foreach (String fileType in FileTypes)
picker.FileTypeFilter.Add("." + fileType);
var list = await picker.PickMultipleFilesAsync();
FYI Your manifest must declare "Music Library" in Capabilities

Access to the path is denied in Windows Store application

I create Windows Store application. In MainPage.xaml.cs I want to get data from xml file, but I get error message on line:
XDocument document = XDocument.Load(filename).
UnauthorizedAccessException was unhandled by user code
Access to the path 'C:\Events Project\events.xml' is denied.
Any advice is appreciated.
MainPage.xaml.cs
private EventMan man = new EventMan();
public MainPage()
{
this.InitializeComponent();
this.LoadEvents();
}
private void LoadEvents()
{
this.Events = man.GetAllEvents(#"C:\Events Project\events.xml");
}
EventMan.cs
public List<Event> GetAllEvents(string filename)
{
if (filename == null)
{
throw new ArgumentNullException("filename");
}
XDocument document = XDocument.Load(filename);
...
}
You can only access certain locations with Windows Store apps by default, as explained here:
File access and permissions in Windows Store apps
You can put the file in your app's AppData folder. Then you can use the ApplicationData class to freely access the file from there...
var file = await ApplictionData.Current.LocalFolder.GetFileAsync("events.xml");

A problem with Relative Path Resolution when setting an Image Source

I have built a small WPF application that allows users to upload documents and then select one to display.
The following is the code for the file copy.
public static void MoveFile( string directory, string subdirectory)
{
var open = new OpenFileDialog {Multiselect = false, Filter = "AllFiles|*.*"};
var newLocation = CreateNewDirectory( directory, subdirectory, open.FileName);
if ((bool) open.ShowDialog())
CopyFile(open.FileName, newLocation);
else
"You must select a file to upload".Show();
}
private static void CopyFile( string oldPath, string newPath)
{
if(!File.Exists(newPath))
File.Copy(oldPath, newPath);
else
string.Format("The file {0} already exists in the current directory.", Path.GetFileName(newPath)).Show();
}
The file is copied without incident. However, when the user tries to select a file they just copied to display, A file not found exception. After debugging, I've found that the UriSource for the dynamic image is resolving the relative path 'Files{selected file}' to the directory that was just browsed by the file select in the above code instead of the Application directory as it seems like it should.
This problem only occurs when a newly copied file is selected. If you restart the application and select the new file it works fine.
Here's the code that dynamically sets the Image source:
//Cover = XAML Image
Cover.Source(string.Format(#"Files\{0}\{1}", item.ItemID, item.CoverImage), "carton.ico");
...
public static void Source( this Image image, string filePath, string alternateFilePath)
{
try
{image.Source = GetSource(filePath);}
catch(Exception)
{image.Source = GetSource(alternateFilePath);}
}
private static BitmapImage GetSource(string filePath)
{
var source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri( filePath, UriKind.Relative);
//Without this option, the image never finishes loading if you change the source dynamically.
source.CacheOption = BitmapCacheOption.OnLoad;
source.EndInit();
return source;
}
I'm stumped. Any thought's would be appreciated.
Although I don't have a direct answer, you should use caution for such allowing people to upload files. I was at a seminar where they had good vs bad hackers to simulate real life exploits. One was such that files were allowed to be uploaded. They uploaded malicious asp.net files and called the files directly as they new where the images were ultimately presented to the users, and were able to eventually take over a system. You may want to verify somehow what TYPES of files are being allowed and maybe have stored in a non-exeucting directory of your web server.
It turns out I was missing an option in the constructor of my openfiledialogue. The dialogue was changing the current directory which was causing the relative paths to resolve incorrectly.
If you replace the open file with the following:
var open = new OpenFileDialog{ Multiselect = true, Filter = "AllFiles|*.*", RestoreDirectory = true};
The issue is resolved.

Categories