Skip to main content

Blog

Go Search
Home
  

Categories
Work
Personal
Other Blogs
There are no items in this list.
Blog of Ralph Arvesen, containing my thoughts, comments and questions.
Photos, Iron Maiden
I saw Iron Maiden recently, here are some photos if you are interested.

image
Toad home
I propagate a lot of plants. Some toads have decided my seedling pots make nice resting spots... I found 3 toads in separate pots.

image
Call Silverlight from JavaScript, call JavaScript from Silverlight
The following demonstrates how to call JavaScript from Silverlight managed code, and Silverlight managed code from JavaScript. Note this is using a beta version of Silverlight which can (and probably will) change in the future.

The main points are...

In the JavaScript code:
  • Use document.getElementById to get the Silverlight control.
  • Then call Content.<registered name>.<method name>. For example, control.Content.Page.UpdateText(text).
  • Nothing special for the functions that are called from Silverlight.
In the Silverlight code:
  • Mark the class with the ScriptableType attribute.
  • Call HtmlPage.RegisterScriptableObject in the constructor.
  • Mark any methods that will be called from JavaScript with ScriptableMember.
  • Use HtmlPage.Window.Invoke to call JavaScript functions.
Here are more detailed steps to call JavaScript and Silverlight code.

Call Silverlight method from JavaScript

1) Add XAML elements to the Silverlight control. This displays the string passed in from JavaScript.
<StackPanel VerticalAlignment="Top" Orientation="Horizontal">
  <TextBox x:Name="Result" HorizontalAlignment="Stretch" Width="200" Height="24" />
</StackPanel>
2) Make the object accessible to JavaScript by specifying the ScriptableType attribute and calling RegisterScriptableObject.
[ScriptableType]
public partial class Page : UserControl
{
    public Page()
    {
        InitializeComponent();

        // make this object a scriptable object
        HtmlPage.RegisterScriptableObject("Page"this);            
    }
3) Add the method that is called from JavaScript and specify the ScriptableMember attribute.
// called from javascript
[ScriptableMember]
public void UpdateText(string result)
{
    this.Result.Text = result;
}
4) Add HTML elements to the web page.
<!-- html area, click on the link to send data to the Silverlight control -->
<input id="result" type="text" size="30" />&nbsp;&nbsp;
<a href="javascript:updateSilverlight();">Update Silverlight</a>
5) Update the ID for the Silverlight control. This is not necessary, but you might want to use something besides the default XAML1.
<asp:Silverlight ID="silverlightControl" ... />
6) Add the JavaScript function that calls the Silverlight managed code method.
function updateSilverlight()
{
    // get data from html control
    var text = document.getElementById("result").value;

    // call silverlight control method
    var control = document.getElementById("silverlightControl");
    control.Content.Page.UpdateText(text);
}
Now you can run the application. Enter some text in the HTML textbox and press the Update Silverlight link. The JavaScript function updateSilverlight is executed which calls the managed code UpdateText method.

image


Call JavaScript function from Silverlight

1) Add the JavaScript function that will be called.
// called from silverlight
function updateText(text)
{
    document.getElementById("result").value = text;

2) Add a button element to the XAML.
<StackPanel VerticalAlignment="Top" Orientation="Horizontal">
  <TextBox x:Name="Result" HorizontalAlignment="Stretch" Width="200" Height="24" />
  <Button x:Name="CallJavaScript" Content="Update JavaScript"
     Width
="130" Height="24" Margin="10,0,0,0" Click="CallJavaScript_Click" />

</StackPanel>
3) Implement the click handler in the code-behind file.
private void CallJavaScript_Click(object sender, RoutedEventArgs e)
{
    // call the javascript function
    HtmlPage.Window.Invoke("updateText"this.Result.Text);
}
Now run the application again. Enter some text in the Silverlight textbox and click the Update JavaScript button. The click handler is executed which uses the HtmlPage.Window.Inovke method to execute the JavaScript updateText function.

image

Set cookies in Silverlight
Here is a simple class that demostates how to set cookies from a Silverlight application.
public static class Cookie
{
    // set cookie without expiration
    public static void Set(string name, string value)
    {
        HtmlPage.Document.Cookies = string.Format("{0}={1};", name, value);
    }

    // set the cookie with expiration
    public static void Set(string name, string value, DateTime expires)
    {
         HtmlPage.Document.Cookies = string.Format(
            "{0}={1}; expires={2}, {3} {4} {5} {6}:{7:00}:00 UTC",
            name, value, expires.DayOfWeek.ToString(),
            expires.Day, expires.Month, expires.Year,
            expires.Hour, expires.Minute);
    }
    
    // see if the cookie exists
    public static bool Exists(string name, string value)
    {
        return HtmlPage.Document.Cookies.Contains(
            string.Format("{0}={1}", name, value));
    }
}
Sample usage.
// set the cookie
Cookie.Set("SomeSetting""True"DateTime.UtcNow.AddDays(7));
            
// see if cookie is set
bool result = Cookie.Exists("SomeSetting""True");

Set default browser for Visual Studio projects
I started working on a web (Silverlight) project after years of creating desktop applications, so this might be common knowledge... I use Firefox as my browser but I want to use Internet Explorer when testing / debugging the web project I'm working on. You can do this by:
  • In the Visual Studio project, right click on a web page (an .aspx file).
  • Select Browse With...
  • Set Internet Explorer as the default.
image
Now Firefox is still my default browser, but Internet Explorer is the default browser within Visual Studio.
TeraCopy, file transfer utility for Vista
I have had various problems copying files from network and external drives with Vista, I don't recall the exact problem, but the file transfer would fail for one reason or another. I have been using a free utility called TeraCopy which has solved the problem, I can copy large files from one system to another... pretty much like I could with XP.
CreateTV, PBS how-to programs
imageFor the many, several, couple, the other person, that gets TV from an over-the-air antenna, you might check your other PBS digital channels. The Austin PBS channel started broadcasting CreateTV on their second digital signal 18.2. CreateTV is a collection of how-to PBS programs. I find some useful, but it would be great if they also broadcast a science-nature-history channel, with programs such as Nova, Nature, and American Experience.

CreateTV might be available on cable and satellite, I would check but I need to climb on the roof and readjust the antenna.
Window loses to big horse head
We walked out to the car last night to find Randy (horse) standing by the car with a pile of shattered glass. It turns out he stuck his head through the back passenger window (which was half way down) to look for food but must have gotten stuck on his way out. Randy was fine, just disappointed that he did not find any food to eat.

image
Feisty Bullsnake
The kids and I came across a Bullsnake the other day. Some are docile, others are quite feisty when they feel threatened.
  • Hiss loudly by sucking in air, and then blowing out.
  • Rattle tail to resemble a rattlesnake.
  • Flatten head to resemble a rattlesnake (pit viper head).
They are harmless and not venomous. Bullsnakes can get up to 7 foot, most adults are 4 - 6 feet. A close relative is the Gopher Snake in the western states. Here are some photos, note that I was messing with (harassing) the snake to get photos, it was not attacking and just wanted to be left alone.

image  image
WPF, binding to an image without file access exceptions
You can run into file access errors when using images in WPF. By default, the .Net Framework locks the image until it's not used and the garbage collector decides to release the reference. For example, the following snippet displays an image but a file access error occurs if the application, or the user, tries to modify or delete the image file from the file system.
<Image Source="d:\vertigo.png" />
You can change how the framework manages the reference to the image with the BitmapImage.CacheOption property. The following snippet specifies that the image is loaded and the reference is released, so the image on the file system can be modified or deleted.
<Image>
  <Image.Source>
    <BitmapImage UriSource="d:\vertigo.png" CacheOption="OnLoad"></BitmapImage>
  </Image.Source>
</Image>
But the UriSource property does not support binding, so you cannot do something simple like the following:
<Image>
  <Image.Source>
    <!-- this does not work -->
    <BitmapImage UriSource="{Binding Path=ImagePath}" CacheOption="OnLoad"></BitmapImage>
  </Image.Source>
</Image>
Instead, you can do your own UriSource binding by creating a converter that takes in a path to the image and returns a BitmapImage object. For example, the following XAML binds the Source property to ImagePath (which is the path to the image), along with a converter that returns a BitmapImage object.
<local:ImagePathConverter x:Key="ImagePathConverter"/>
<Image Source="{Binding Path=ImagePath, Converter={StaticResource ImagePathConverter}}" />
The converter is pretty straightforward: creates a BitmapImage object, sets the CacheOption property, and returns the object. So now you can data bind to an image and still modify or delete the image from the file system without file access errors.
public class ImagePathConverter : IValueConverter
{
    public object Convert(object value, Type targetType, 
        object parameter, System.Globalization.CultureInfo culture)
    {
        // value contains the full path to the image
        string path = (string)value;

        // load the image, specify CacheOption so the file is not locked
        BitmapImage image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.UriSource = new Uri(path);
        image.EndInit();

        return image;
    }

    public object ConvertBack(object value, Type targetType, 
        object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException("The method or operation is not implemented.");
    }

1 - 10 Next

 ‭(Hidden)‬ Admin Links