HowTo: Save a file from Silverlight using the SaveFileDialog

Saving a file from Silverlight using the SaveFileDialog, added in Silverlight 3, is easy. If you’re used to desktop development however, you might find yourself getting a SecurityException with the message ‘File operation not permitted. Access to path ‘xxx’ is denied.’. Here’s why:

In desktop development, you’re used to getting a filename from a SaveFileDialog. Next, you start doing whatever you need to be doing to the file, based on the filename. This would look something like this:

SaveFileDialog saveFileDialog = new SaveFileDialog();

if (saveFileDialog.ShowDialog() == true)
{
    StreamWriter streamWriter = new StreamWriter(saveFileDialog.SafeFileName);
    streamWriter.Write("Follow me on twitter: @rickvdbosch");
    streamWriter.Flush();
    streamWriter.Close();
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

This results in the SecurityException. First time I saw the property, I genuinely thought it said SaveFileName. But, as you can see, it says SafeFileName. It is named safe, because the returned file name has all file path information removed for security purposes.

In Silverlight, if you want the above functionality, it should look something like this:

SaveFileDialog saveFileDialog = new SaveFileDialog();

if (saveFileDialog.ShowDialog() == true)
{
    StreamWriter streamWriter = new StreamWriter(saveFileDialog.OpenFile());
    streamWriter.WriteLine("Follow me on twitter: @rickvdbosch");
    streamWriter.Flush();
    streamWriter.Close();
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }The OpenFile method opens the file specified by the SafeFileName returning a Stream, giving you the opportunity to save whatever you want to save over there.

Hope this helps.

On a side note: the ‘== true’ part in the if condition is needed in this case. Because the ShowDialog method returns a nullable boolean it is not enough to use saveFileDiaolog.ShowDialog() in the condition. Just so you know… :)

HowTo: open all files from the Find Results window

Here’s a quick Visual Studio tip for you…

I frequently search for a specific text in my solution because I need to do something in all places where that text occurs. Today I found out how you can open all the files that are mentioned in the Find Results window.

Search for the text you’re looking for. In my case this is ITest*.
Open up the Search Results window and select all the records where the text was found. You can do this by dragging your mouse cursor over the text or clicking the text of the first search result, holding SHIFT and clicking the text of the last.
Search Results for ITest

Right click anywhere on the selected text and choose ‘Go to location’. If you click anywhere other than on selected text, you will lose the selection and you’ll probably get just one file opened. When all files are opened you will keep the ‘Go To Next Location F8’ and ‘Go To Previous Location SHIFT + F8’ functionality. That might be a nice one to loop through all the locations where your text was found. Especially when it was found more than once in one file.

Hope this helps.

 

* The usefulness of searching for this interface is arbitrary due to functionality as ‘Find all references’ and so on. Luckily I’m only using it for this example. So lets not focus on that but on the tip this post is about ;)

HowTo: have Visual Studio open XAML documents in code view

Just a small post to start the new year… and let it be a good one!

When opening a XAML document in Visual Studio, it opens in split view by default. This might become annoying when you have a large XAML document, because all the content needs to be rendered before you can get some work done.

Here’s how you can have Visual Studio open XAML documents in code view:

  • Go to Tools, Options
  • Under Text Editor open the XAML section and select Miscellaneous
  • Under Default View check the Always open documents in full XAML view box (see image below)
  • Click OK to apply and you’re all done!

Hope this helps.

fullxamlview

Visual Studio: Zero-impact Projects & Cutting/copying empty lines

Yesterday I remembered two Visual Studio options Sara Ford told about in a presentation of her I attended a while back. Changing them made me happy… :)

Zero-impact projects
When I have to test something real quick, I tend to create a new project in Visual Studio and scribble some code to test whatever I want to test at that point. This causes my project directory to be filled with projects named ‘WindowsFormsApplication14’ or something like that. To make this stop, go to Tools – Options – Projects and Solutions – General. Uncheck the option ‘Save new projects when created’. This way those newly made (and shortly used) projects aren’t saved untill you explicitly tell Visual Studio to do so. No more ‘WindowsFormsApplication63’ for you! Unless you want to name it that way intentionally, of course…

Cutting/copying empty lines
We probably all experienced this at one time or another: you select some code, copy it, go to an empty line where you want to past the code…….and you press CTRL + C by accident. With the default settings, you just copied an empty line and have lost the stuff you copied earlier. But with this next option, empty lines won’t get copied or cut anymore! Go to Tools – Options – Text Editor – All languages (or just the language you want to change this setting for) and deselect the option ‘Apply Cut or Copy commands to blank lines when there is no selection’.

Running Windows Vista on a MacBook Pro

When installing Windows Vista on a MacBook Pro, the default driver for the Wireless Network Adapter doesn’t function properly. To get the Wireless Network Adapter to work, first install the Boot Camp Services by inserting your OS X DVD and running the setup. Next you need to install the Boot Camp 2.1 update. You can download that one by running Apple Software Update, which is installed as part of the Boot Camp Services. And that’s where things go wrong… The Boot Camp update installation downloads properly, but doesn’t complete.

The reason the update doesn’t install properly? The Boot Camp 2.1 update is American only and therefore expects to find a key in the registry with the decimal value 1033 (American English). Since the Windows version we installed was Dutch, the update couldn’t complete.

How to fix this issue
To fix this problem, follow the steps below:

  • Open the registry editor
  • Search for the ProductName key with the value ‘Boot Camp Services’ (for the Dutch version, this was ‘Boot Camp-Services’), located under HKEY_CLASSES_ROOTInstaller and then some…
  • Double click the Language key in that same location to open it
  • Change the value to 409 (Hex) or 1033 (Decimal)
  • Reboot the machine and install the Boot Camp update
  • That’s it!

Hope this helps.

By |July 10th, 2009|HowTo|0 Comments

HowTo: Add a body onload script to a page that uses a MasterPage

When you use a MasterPage to define the design of your website, you might come across the problem that there is no body element in a web content form. This can be a problem when you want to add an onload script to a specific page. You could of course add the onload on the MasterPage, but you might not want the script to run on every page. There are several workarounds to fix this ‘problem’. The one I used last week was to do the following:

  1. Add the runat=”server” tag on the body in the MasterPage
  2. Add a unique ID on the body in the MasterPage
  3. Add a method to the MasterPage to set the onload for the body. This might look a bit like this (of course you can also have the script for the load be a parameter for the method):
       1: internal void SetBodyLoad()
       2: {
       3:     MasterPageBody.Attributes.Add("onLoad", "initialize()");
       4: }
  4. Add this line of code in the Page_Load of the page you want to have the onload:
       1: ((MasterPageName)Master).SetBodyLoad();

 

This worked for me! Hope this helps.

By |January 30th, 2009|.Net, HowTo|1 Comment

The absolute minimum every software developer …

One of the posts that is being read quite frequently over here is HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string). One of the (many) reactions to that post was from one Simucal, stating:

Also, to the original poster, Rick van den Bosch… shame on you for using ASCIIEncoding.Default.GetBytes().  You do realize that would seriously restrict the usefulness of your method to working only in languages that ASCII has the character sets for, right?

I suggest you read this article entitled:

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

Yes, I do realize that using ASCIIEncoding.Default.GetBytes() would seriously restrict the usefulness of the method to working only in languages that ASCII has the character sets for. The primary reason for the post was to illustrate the way to calculate the hash. Representing it as a string was only there to be complete for a specific scenario. I did not try to write a hashing function for every language ;)

That being said, the post Simucal refers to is a good one, and it truly is the absolute minimum every software developer absolutely, positively must know about unicode and character sets. And I guess there are no excuses ;). So if you haven’t done so already, go and read it.

Backing up and restoring Visual Studio settings

When roaming the MSDN forums for unanswered questions for me to answer, I come across a lot of questions about any of the following:

  • Intellisense acting weird
  • Intellisense not showing up at all
  • Menu items that are all garbled up
  • Missing buttons on toolbars
  • Complete toolbars missing
  • Keyboard shortcuts acting weird
  • Keyboard shortcuts not working at all

In most cases, resetting the Visual Studio settings to the default settings using devenv /resetsettings solves any problems that are in that list. But I can imagine you don’t want to go through the hassle of setting up Visual Studio exactly the way you want it again (and again, and…). There’s a solution to that: define your own settings file to restore settings from.

To create a file with your settings, first install Visual Studio (if you hadn’t done so already) and adjust all settings to accomodate your needs. Next, select ‘Tools’ and ‘Import and export settings’. This pops up an import export wizard, where you can choose the ‘Export selected environment settings’ option to create your own settings file. On the next screen, select the settings you want to be able to reset later on. After pressing next, enter a filename to store the settings in and click finish. That’s it!
Restoring your settings is as easy as exporting is: open up the wizard, choose if you want to backup the current settings, select the settingsfile you want to import, select the settings to restore and click finish.

Besides using the import export wizard, you can also use the /resetsettings command line switch to reset to a specific set of settings in a file by specifying that file like so:
Devenv.exe /ResetSettings “C:My FilesMySettings.vssettings”

Technorati tags: ,

LinkButton inside UpdatePanel results in full postback, UpdatePanel not triggered

When you dynamically generate a LinkButton in code that will be placed inside an UpdatePanel, you’ll experience that the Click event for the LinkButton results in a full postback in stead of the UpdatePanel being triggered. There’s a rather simpel solution to this problem…

First, let’s take a look at the scenario. Consider this HTML:
HTML_markup
There’s a literal control outside of the UpdatePanel. There’s a second literal control inside the UpdatePanel. Besides that, there is a PlaceHolder inside the UpdatePanel, where the generated LinkButton will be placed. The parent control doesn’t have to be a PlaceHolder, it can also be a repeater or something like that.

Next, consider this code:
linkbutton_code
As you can see, a LinkButton is generated and added to the PlaceHolder in every PageLoad. In the same PageLoad, the literal outside of the UpdatePanel is updated. The literal inside the UpdatePanel is only updated when the LinkButton is clicked. This makes for something like this for the first time the page loads:
first_load 
and something like this after the LinkButton is clicked:
lbclicked_load 
Because the LinkButton is inside the UpdatePanel, you would think hitting it would trigger the UpdatePanel so only the literal control inside the UpdatePanel gets updated. The fact that the two literals have the same time on it in the ‘after LinkButton clicked’ image, shows that the entire page was posted back.
The problem here is in the fact that the ID for the LinkButton is not set in the code. Weird thing is that when you change the code to generate a normal ASP.NET Button (with or without an ID), the problem doesn’t occur. This has something to do with the fact that both the input rendered for the button and the link rendered for the linkbutton have no ID, but the input control does have a name that can be used to relate events/postbacks to. The link doesn’t have that either, so I’m guessing it has something to do with that.

So the solution is rather simple. Add a line in code where the ID for the control is set (like linkButton.ID = “TestLinkButton”;) After clicking the linkbutton in my example, only the literal in the UpdatePanel is updated. Hooray! ;)
lbclicked2_load 


kick it on DotNetKicks.com


Technorati tags: ,,

Getting the ModalPopupExtender to work in SharePoint 2007

Getting the ModalPopupExtender from the Ajax Control Toolkit to work (decently) in SharePoint was not exactly a walk in the park. With a default SharePoint installation, the modal popup is partly positioned ‘outside’ of the page (you only see the bottom right part of the popup in the top left corner of the browser). Postbacks are not executed or executed poorly and the page gets garbled up. A possible solution for the positioning of the popup is to set the X and Y property of the ModalPopupExtender. Downside is you never know (for sure) if the popup is positioned inside the visible part of the browser because of things like non-maximized browser, different resolutions and so on.
Today we seem to have solved our issues with the ModalPopupExtender in SharePoint. We haven’t tested it in all scenario’s yet, but we’ll get to that. At this point everything looks the way it is supposed to. And it seems to work, too… ;).

The extra steps we took to make these two play together the way we wanted them to, besides the usual steps to make Ajax work in ASP.NET 2.0, are:

* Because of our setup with close-images that postback (because we have to clear controls and that sort of stuff) and more, we couldn’t use the TargetControlID property for the ModalPopupExtender. Well, we could, but that would result in the background not being displayed properly half the time ;). This can be solved by setting the TargetControlID to a dummy control (like a hidden one) and showing the popup from code.

** We have a usercontrol with several usercontrols in it. This one usercontrol (the parent) was added to a page. The normal (postback) controls on the usercontrols didn’t work after one of the modal popups was shown. And I can image neither would any other ‘normal’ controls on the page, but we didn’t encounter this scenario. The problem was the page would freeze with a message in the taskbar stating ‘The page is busy submitting data to the server’ directly after an Ajax postback. The controls that performed a ‘normal’ postback did nothing: the serverside code just was not executed. We solved this by putting an updatepanel around everything inside the usercontrol. That way the normal controls would postback in an ajaxy way too, apparently solving the ‘The page is busy’ message.

We’ll be testing this solution over the next few days. If any problems pop up, I’ll keep you posted.