Where are files saved while debugging a Silverlight 5 Application in Internet Explorer 10? - debugging

I have some code that saves an xml file to the file system.
public static void Save(T obj, string FileName)
{
if (Application.Current.HasElevatedPermissions)
{
string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string path = System.IO.Path.Combine(myDocuments, FileName);
using (var writer = new StreamWriter(path))
{
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, obj);
writer.Flush();
}
}
else
{
throw new Exception("Cannot Save File. Application Requires Elevated permissions.");
}
}
While debugging using Internet Explorer 10 the file is not saved to the listed path in the path variable "C:\Users\Travis\Documents\Save.xml"
I call load with the exact same path "C:\Users\Travis\Documents\Save.xml" and the file loads correctly but the file still does not exist at the listed location.
I searched the file system with no results for Save.xml but it has to exist since it is able to load after application exit.
If I access the same page using Chrome the file is created successfully at the location.
I am wondering where Internet Explorer saves the file?

I found that if I uncheck "Enable Protected Mode" in IE's Security tab then the file is created in the location as expected.

Related

How to include resources to application for windows phone?

I have a problem: I created new c# project for windows phone (in VS 2013) and set test file property as "Copy if newer", but I cannot see file in emulator's Local folder. What do I do wrong?
More detailed:
Create app:
File->New->Project->Templates->Visual C#->Store Apps->Windows Phone Apps->Blank App (Windows Phone)
set test file property
run on emulator (there is a button for this) and list files with code:
async void listFolder()
{
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
Stack<StorageFolder> stack = new Stack<StorageFolder>();
stack.Push(local);
StorageFolder current;
string path;
byte[] bytes;
StorageFile logFile = await local.CreateFileAsync("log.txt", CreationCollisionOption.ReplaceExisting);
using (var s = await logFile.OpenStreamForWriteAsync())
{
while (stack.Count > 0)
{
current = stack.Pop();
foreach (StorageFolder f in await current.GetFoldersAsync())
{
stack.Push(f);
}
path = current.Path;
bytes = Encoding.UTF8.GetBytes(current.Path + "\n");
s.Write(bytes, 0, bytes.Length);
foreach (StorageFile f in await current.GetFilesAsync())
{
bytes = Encoding.UTF8.GetBytes(f.Path + "\n");
s.Write(bytes, 0, bytes.Length);
}
s.Flush();
}
}
}
Check file with Windows Phone Power Tools. Local folder contains log.txt only. Log contains Local directory and log file. No TestText.txt
How do I include file to application and access it on emulator?
Limitations:
I do need to held data on local storage (no web links, no cloud)
If you want to access files that come with your package, then you need to use Package.InstalledLocation, you won't find those files in ApplicationData.LocalFolder.
Note that files included in Package are read-only and you won't be able to write them.
Some more information you will also find at this answer.

Saving custom Word document using FilePicker in Windows Store app

I am making a Windows Store application and I want to allow users that press an "Export To Word" button to have all the data that they have input into the app to be displayed in a Word document and saved to a desired location on their computer. The code below is a test segment of code that almost does what I am after, however after saving the document and opening it using Word rather than the app, it cannot open the file due to it being corrupted apparently. However when you open it in Notepad the text is displayed as I want.
private async void exportToWord_Click(object sender, RoutedEventArgs e)
{
await ExportToWord();
}
private async Task ExportToWord()
{
// Create the picker object and set options
Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Word", newList<string>{".docx"});
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "Test";
Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
MessageDialog mD;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish
// making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.DeferUpdates(file);
// write to file
await Windows.Storage.FileIO.WriteTextAsync(file, createContentsOfFile());
// 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.
Windows.Storage.Provider.FileUpdateStatus updateStatus = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
if (updateStatus == Windows.Storage.Provider.FileUpdateStatus.Complete)
{
mD = newMessageDialog("Connect exported to:" + file, "Export Successful");
}
else
{
mD = newMessageDialog("Could not save file. Try again", "Export Unsuccessful");
}
}
else
{
mD = newMessageDialog("Operation canceled because the file could not be found. Try again", "Export Unsuccessful");
}
await mD.ShowAsync();
}
private string createContentsOfFile()
{
return "Testing...";
}
I believe the issue is that I am outputting plain text to the Word document but it needs to be in a certain format to be output correctly and be displayed in a Word doc. Is there any way of doing this in Windows Store apps?
Any help would be appreciated.
I'm not aware of any Word doc components available for Windows Runtime apps (Microsoft doesn't provide one, but there could be a third party component I'm not aware of).
You can get documentation on the docx format and for simple text it may not be too complex (I'm not sure), or you can use another format which Word can open.
If you don't need formatting I'd probably stick with txt.
If you need small amounts of formatting then rtf is a good option. It is fairly simple to generate yourself or the RichEditBox can export RTF format text which you can then save into a .doc file and open in Word.

NotifyFilter of FileSystemWatcher not working

I have a windows service (and verified the code by creating a similar WinForms application) where the NotifyFilter doesn't work. As soon as I remove that line of code, the service works fine and I can see the event-handler fire in the WinForms application.
All I'm doing is dropping a text file into the input directory for the FileSystemWatcher to kick off the watcher_FileChanged delegate. When I have the _watcher.NotifyFilter = NotifyFilters.CreationTime; in there, it doesn't work. When I pull it out, it works fine.
Can anyone tell me if I'm doing something wrong with this filter?
Here is the FSW code for the OnStart event.
protected override void OnStart(string[] args)
{
_watcher = new FileSystemWatcher(#"C:\Projects\Data\Test1");
_watcher.Created += new FileSystemEventHandler(watcher_FileChanged);
_watcher.NotifyFilter = NotifyFilters.CreationTime;
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
_watcher.Error += new ErrorEventHandler(OnError);
}
private void watcher_FileChanged(object sender, FileSystemEventArgs e)
{
// Folder with new files - one or more files
string folder = #"C:\Projects\Data\Test1";
System.Console.WriteLine(#"C:\Projects\Data\Test1");
//Console.ReadKey(true);
// Folder to delete old files - one or more files
string output = #"C:\Temp\Test1\";
System.Console.WriteLine(#"C:\Temp\Test1\");
//Console.ReadKey(true);
// Create name to call new zip file by date
string outputFilename = Path.Combine(output, string.Format("Archive{0}.zip", DateTime.Now.ToString("MMddyyyy")));
System.Console.WriteLine(outputFilename);
//Console.ReadKey(true);
// Save new files into a zip file
using (ZipFile zip = new ZipFile())
{
// Add all files in directory
foreach (var file in Directory.GetFiles(folder))
{
zip.AddFile(file);
}
// Save to output filename
zip.Save(outputFilename);
}
DirectoryInfo source = new DirectoryInfo(output);
// Get info of each file into the output directory to see whether or not to delete
foreach (FileInfo fi in source.GetFiles())
{
if (fi.CreationTime < DateTime.Now.AddDays(-1))
fi.Delete();
}
}
I've been having trouble with this behavior too. If you step through the code (and if you look at MSDN documenation, you'll find that NotifyFilter starts off with a default value of:
NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite
So when you say .NotifyFilter = NotifyFilters.CreationTime, you're wiping out those other values, which explains the difference in behavior. I'm not sure why NotifyFilters.CreationTime is not catching the new file... seems like it should, shouldn't it!
You can probably just use the default value for NotifyFilter if it's working for you. If you want to add NotifyFilters.CreationTime, I'd recommend doing something like this to add the new value and not replace the existing ones:
_watcher.NotifyFilter = _watcher.NotifyFilter | NotifyFilters.CreationTime;
I know this is an old post but File Creation time is not always reliable. I came across a problem where a Log file was being moved to an archive folder and a new file of the same name was created in it's place however the file creation date did not change, in fact the meta data was retained from the previous file (the one that was moved to the archive) .
Windows has this cache on certain attributes of a file, file creation date is included. You can read the article on here: https://support.microsoft.com/en-us/kb/172190.

how to programmatically kick off a ssis package in asp.net MVC3 to import excel files

I am having some trouble with a asp.net MVC3 web application that I am developing. I need an upload page which Allows the user to upload excel files and dump them to the file system. I got this to work fine. The next part is the part that I am having trouble with, After I upload the excel files I need to programmatically kick off a SSIS package which I have created already to import the excel files.
Here is what I have so far in code:
//
// POST: /Home/Update/
[HttpPost]
public ActionResult Update(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
ViewBag.Message = "File Uploaded Successfully";
file.SaveAs(path);
}
//Start the SSIS here
try
{
Application app = new Application();
Package package = null;
package = app.LoadPackage( #"C:\Users\Chris\Documents\Visual Studio
2008\Projects\Integration Services Project1\Integration Services Project1
\bin\Package.dtsx", null);
// Execute Package
DTSExecResult results = package.Execute();
if(results == DTSExecResult.Failure)
{
foreach(DtsError local_DtsError in package.Errors)
{
ViewBag.Message("Package Execution results:{0}",
local_DtsError.Description.ToString());
}
}
}
catch(DtsException ex)
{
//ViewBag.Message("{0} Exception caught.", ex);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Update");
}
When I run the code and upload an excel file I get a DtsException caught, which says:
Failed to open package file "C:\Users\Chris\Documents\Visual Studio 2008\Projects\Integration Services Project1\Integration Services Project1\bin\Package.dtsx" due to error 0x80070003 "The system cannot find the path specified.". This happens when loading a package and the file cannot be opened or loaded correctly into the XML document. This can be the result of either providing an incorrect file name was specified when calling LoadPackage or the XML file was specified and has an incorrect format.
I don't understand why it is giving me this because the file path is right I checked and it is exactly correct. I need some help fixing this issue I would greatly appreciate any help you guys can give.
Permissions I should think. Put the file somewhere where account running IIS can see it. Whereever you were planning on deploying it, would be good.

Silverlight 4 dynamically downloaded satellite assembly problem

I am dynamically downloading a XAP file that has an embedded resource assembly, with a single resource file (ApplicationStrings.fr-CA.resx). I am using WebClient to pull down the XAP file and using the following code to load the assembly, based on work done by Jeff Prosise in this post: http://www.wintellect.com/CS/blogs/jprosise/archive/2010/06/21/dynamic-localization-in-silverlight.aspx.
Note that I also manually create the XAP file from the fr-CA folder with assembly and the ApplicationManifest.xaml, as described by Guy Smith-Ferrier's steps listed in his presentation here http://www.guysmithferrier.com/post/2010/10/Building-Localized-XAP-Resource-Files-For-Silverlight-4.aspx.
// Get the application manifest from the downloaded XAP
StreamResourceInfo sri = new StreamResourceInfo(e.Result, null);
XmlReader reader = XmlReader.Create(Application.GetResourceStream(sri, new Uri("AppManifest.xaml", UriKind.Relative)).Stream);
AssemblyPartCollection parts = new AssemblyPartCollection();
// Enumerate the assemblies in the downloaded XAP
if (reader.Read())
{
reader.ReadStartElement();
if (reader.ReadToNextSibling("Deployment.Parts"))
{
while (reader.ReadToFollowing("AssemblyPart"))
{
parts.Add(new AssemblyPart() { Source = reader.GetAttribute("Source") });
}
}
}
// Load the satellite assemblies
foreach (AssemblyPart part in parts)
{
if (part.Source.ToLower().Contains("resources"))
{
Stream assembly = Application.GetResourceStream(sri, new Uri(part.Source, UriKind.Relative)).Stream;
part.Load(assembly);
}
}
// Change the culture
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
The assembly seems to load ok, and I have matched up namespaces with the default resource file (ApplicationStrings.resx) with the downloaded resource file (ApplicationStrings.fr-CA.resx). As seen the code, the culture is set for the current thread.
However, calls to ApplicationStrings.ResourceManager.GetString(...) do not return the resources for the set culture. For example, the following should return a string for the new culture (fr-CA), but always returns the default culture (en-US).
/// <summary>
/// Looks up a localized string similar to User Name:.
/// </summary>
public static string Label_UserName {
get {
return ResourceManager.GetString("Label_UserName", resourceCulture);
}
}
Any suggestions? Thanks.
** UPDATE
I figured it out...I had forgotten to reset my supported locals in my satellite assembly project file:
<SupportedCultures>fr-CA</SupportedCultures>
I also made my folder structure exactly as it is for the default resources in my main Silverlight application.

Resources