Run the MSI file in the UWP application - windows-store-apps

I have an UWP application, In that I need to run the MSI file on the button click.
I don't think UWP will support "process.start(filename)". Is it possible in UWP to achieve this?.

The UWP cant open MSI.
But uwp can open the other type file.
You can use Launcher.
Pick the msi that you want run.
Run msi by launcher file.
The result is always failed.
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
//pick msi file
FileOpenPicker pick = new FileOpenPicker();
pick.FileTypeFilter.Add(".msi");
StorageFile file = await pick.PickSingleFileAsync();
//run
bool result = await Launcher.LaunchFileAsync(file);
if (result)
{
//success
}
}
But you will see the result is false ,because Many file types that contain executable code, for example .exe, .msi, and .js files, are blocked from launching
You can open the folder and make the use to click the msi file.The code is:
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
//pick msi file
var pick = new FileOpenPicker();
pick.FileTypeFilter.Add(".msi");
var file = await pick.PickSingleFileAsync();
//run
var result = await Launcher.LaunchFileAsync(file, new LauncherOptions
{
TreatAsUntrusted = true,
DisplayApplicationPicker = true
});
if (result)
{
//success
}
else
{
//alway failed
var folder = await file.GetParentAsync();
if (folder != null)
{
await Launcher.LaunchFolderAsync(
folder, //if you can get the file's parent
new FolderLauncherOptions
{
ItemsToSelect = {file}
});
}
}
}
See:Windows Store App running .msi installer
https://msdn.microsoft.com/en-us/library/windows/apps/hh701471.aspx?f=255&MSPPError=-2147217396

Related

How to call a get REST API from a tvOS Application using Xamarin?

I am trying to call a get REST API from my tvOS application. Following is my code when tap the Button:
async void ButtonClicked(UIButton sender)
{
try
{
HttpClient client = new HttpClient();
var response = await client.GetAsync("rest api url");
if (response.IsSuccessStatusCode)
{
var Response = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
if (!string.IsNullOrWhiteSpace(Response.ToString()))
{
var category = JsonConvert.DeserializeObject<Videos>(Response.ToString());
Debug.WriteLine("count:>>" + category.webContentCategoryList.Count);
}
}
}
catch(Exception e)
{
Debug.WriteLine("Exception:>>"+e);
}
I have installed the system.net.http and newtonsoft.json nuget packages. But when I run the project the application showing Main.cs file like below screenshot:
Am I missing something in this?
UPDATE
I have added breakpoint for the first line inside ButtonClicked function. When I taps the Button, the application showing Main.cs file like above screenshot. It is not hitting the first line of ButtonClicked function.
So the issue is something else, I am not an expert in tvOS applications so I can't figure out. I have uploaded a sample project here.
I have fixed this issue by separating the service call on a new function like below, new function is the async method:
partial void ButtonClicked(UIButton sender)
{
LoadData();
}
async void LoadData()
{
HttpClient client = new HttpClient();
var response = await client.GetAsync("service url");
if (response.IsSuccessStatusCode)
{
var Response = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
if (!string.IsNullOrWhiteSpace(Response.ToString()))
{
var category = JsonConvert.DeserializeObject<Videos>(Response.ToString());
Debug.WriteLine("count:>>" + category.Count);
}
}
}
My XF Thread is here for more details.

PickSaveFileAndContinue: UnauthorizedAccessException on Windows 10 mobile

I am using this code to let users to choose where to save a file:
var fileSavePicker = new FileSavePicker();
fileSavePicker.FileTypeChoices.Add("Pdf", new List<string>(){".pdf"});
fileSavePicker.SuggestedFileName = $"{pdfFile.Name}";
fileSavePicker.SuggestedSaveFile = pdfFile;
fileSavePicker.PickSaveFileAndContinue();
This code works fine on Windows Phone 8.1 but give me an exception (System.UnauthorizedAccessException) when running on Windows 10 mobile. How can I solve this?
When I use FileSavePicker.PickSaveFileAndContinue method in the visual, there is an error “ The FileSavePicker.PickSaveFileAndContinue() is obsolete: instead, use PickSaveFileAsync() ”. So you can use FileSavePicker.PickSaveFileAsync() method in Windows 10 mobile.
Update:
I have test Windows Phone 8.1 on Windows 10 Mobile, it was ok. The code of my project below , you can refer to.
You can also refer to this sample about FileSavePicker.
private void SaveFileButton_Click(object sender, RoutedEventArgs e)
{
// Clear previous returned file name, if it exists, between iterations of this scenario
OutputTextBlock.Text = "";
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";
savePicker.PickSaveFileAndContinue();
}
/// <summary>
/// Handle the returned file from file picker
/// This method is triggered by ContinuationManager based on ActivationKind
/// </summary>
/// <param name="args">File save picker continuation activation argment. It cantains the file user selected with file save picker </param>
public async void ContinueFileSavePicker(FileSavePickerContinuationEventArgs args)
{
StorageFile file = args.File;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write to file
await FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if (status == FileUpdateStatus.Complete)
{
OutputTextBlock.Text = "File " + file.Name + " was saved.";
}
else
{
OutputTextBlock.Text = "File " + file.Name + " couldn't be saved.";
}
}
else
{
OutputTextBlock.Text = "Operation cancelled.";
}
}

background Agent works fine in local environment but failed after app submission to app store

I have an wp8 app using PeriodicTask background Agent.
The task update the information of multiple live tiles,
using POST Client to get title and image url from my server to update the live tile.
Background agent works just fine in debugging and releasing mode. When the .xap file was deployed into my device using XAPDeployement tool, the background Agent also works perfectly.
However, it won't work after submitted to wp app store, no matter it's beta version or not.
If the app is downloaded from store, the background agent has never worked, and it is blocked by system after a few minutes.
How come it goes wrong since the XAP files are the same?
part of code:
public static Task<string> jsonPostClientTask(Dictionary<string, object> parameters, string url)
{
var results = new TaskCompletionSource<string>();
PostClient proxy = new PostClient(parameters);
try
{
proxy.DownloadStringCompleted += (sender, e) =>
{
if (e.Error == null)
{
string response = e.Result.ToString();
results.TrySetResult(response);
}
else
{
results.TrySetResult("");
results.TrySetException(e.Error);
}
};
proxy.DownloadStringAsync(new Uri(url));
}
catch
{
results.TrySetResult("");
}
return results.Task;
}
ScheduledAgent class:
protected override void OnInvoke(ScheduledTask task)
{
foreach (var tile in tileList)
{
string dataString = jsonPostClientTask(parameters, url);
//update tile in used
FlipTileData tileData = new FlipTileData()
{
BackContent = "string content",
WideBackContent = "string back content",
BackBackgroundImage = new Uri("http://xxxx.xxx/xxx.png", UriKind.RelativeOrAbsolute),
WideBackBackgroundImage = new Uri("http://xxxx.xxx/xxx.png", UriKind.RelativeOrAbsolute),
};
ShellTile primaryTile = ShellTile.ActiveTiles.First();
if (primaryTile != null)
primaryTile.Update(tileData);
}
}

Location of folders created in Windows Phone 8

Where do I find the location of the folders and text files I created in windows phone 8. Can we see it in the explorer like we search for the app data in Windows 8? I'm not using IsolatedStorage, instead Windows.Storage. I want to check if the folders and files are created as I want.
This is how I write the file
IStorageFolder dataFolder = await m_localfolder.CreateFolderAsync(App.ALL_PAGE_FOLDER, CreationCollisionOption.OpenIfExists);
StorageFile PageConfig = null;
try
{
PageConfig = await dataFolder.CreateFileAsync("PageConfig.txt", CreationCollisionOption.OpenIfExists);
}
catch (FileNotFoundException)
{
return false;
}
EDIT
try
{
if (PageConfig != null)
{
using (var stream = await PageConfig.OpenStreamForWriteAsync())
{
DataWriter writer = new DataWriter(stream.AsOutputStream());
writer.WriteString(jsonString);
}
}
}
catch (Exception e)
{
string txt = e.Message;
return false;
}
And this is how I read the file from the folder
try
{
var dataFolder = await m_localfolder.GetFolderAsync(App.ALL_PAGE_FOLDER);
var retpng = await dataFolder.OpenStreamForReadAsync("PageConfig.txt");
if (retpng != null)
{
try
{
using (StreamReader streamReader = new StreamReader(retpng))
{
jsonString = streamReader.ReadToEnd();
}
return jsonString;
}
catch (Exception)
{
}
}
}
catch (FileNotFoundException)
{
}
There are also other folders created. I dont receive any exceptions while writing but when I read the string is empty.
Windows.Storage.ApplicationData.LocalFolder(MSDN link here) is another name for Isolated Storage that is in Windows.Storage namespace. The only other location you can access is your app's install directory (and only read-only).
You can use Windows Phone Power Tools to browse what files are in your app's Isolated Storage, or the command line tool that comes with the SDK.
With the help of Windows Phone Power tools, I figured out that there was no text being written in file.
So I converted string to byte and then wrote it to the file and it works! Don't know why the other one does not work though..
using (var stream = await PageConfig.OpenStreamForWriteAsync())
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(jsonString);
stream.Write(fileBytes, 0, fileBytes.Length);
}
The command line tool that comes with Windows Phone SDK 8.0 is Isolated Storage Explorer (ISETool.exe) which reside in "Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Tools\IsolatedStorageExplorerTool" folder for default installation
ISETool.exe is used to view and manage the contents of the local folder

How to download a zip file from a url and extract it on windows phone 8 .The zip file contains compressed sqlite files from server

I am not able to use DownloadDataAsync method.The only option present is DownloadStringAsync method.How can I download a zip file using this method.(I am new to windows phone 8 app development)
I just thought to share the solution that worked for me.
I created a web request to the url given and downloaded the gzip file into isolated storage file.Now after downloading i created a destination file stream and stored the compressed gzip stream file from source file to destination file using WriteByte method of GZipStream.Now we get uncompressed file.
Note:-GZipStream can be added to Visual studio from NuGet manager.
Here is the code snippet which i used to download and extract GZip file.
public async Task DownloadZipFile(Uri fileAdress, string fileName)
{
try
{
WebRequest request = WebRequest.Create(fileAdress);
if (request != null)
{
WebResponse webResponse = await request.GetResponseAsync();
if (webResponse.ContentLength != 0)
{
using (Stream response = webResponse.GetResponseStream())
{
if (response.Length != 0)
{
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
using (IsolatedStorageFileStream file = isolatedStorage.CreateFile(fileName))
{
const int BUFFER_SIZE = 100 * 1024;
byte[] buf = new byte[BUFFER_SIZE];
int bytesread;
while ((bytesread = await response.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
{
file.Write(buf, 0, bytesread);
}
file.Close();
FileStream sourceFileStream = File.OpenRead(file.Name);
FileStream destFileStream = File.Create(AppResources.OpenZipFileName);
GZipStream decompressingStream = new GZipStream(sourceFileStream, CompressionMode.Decompress);
int byteRead;
while ((byteRead = decompressingStream.ReadByte()) != -1)
{
destFileStream.WriteByte((byte)byteRead);
}
decompressingStream.Close();
sourceFileStream.Close();
destFileStream.Close();
PhoneApplicationService.Current.State["DestinationFilePath"] = destFileStream.Name;
}
}
FileDownload = true;
}
}
}
}
if (FileDownload == true)
{
return DownloadStatus.Ok;
}
else
{
return DownloadStatus.Other;
}
}
catch (Exception exc)
{
return DownloadStatus.Other;
}
}
Do you must use DownloadStrringAsync method? otherwise you can check these:
How to extract zipped file received from HttpWebResponse?
download and decompress a zip file in windows phone 8 application
Extract zip file from isolatedstorage
How to download a GZIP file from web to Windows Phone 7 and unzip the contents
To download zip file from the url first there is need to store zip files into isolated storage and after that extract it and read the file as per requirement.
http://axilis.hr/uznip-archives-windows-phone