Archive for November, 2010

Recording the IP address from Silverlight

Silverlight has no native way to get the client’s IP Address. Oh, sad clown of life, how you mock me. So, I had to go and do it myself. Why did I want to do such a thing? Because I was logging the IP Address of visitors to my site under certain conditions – (i.e., if they passed me bogus information, like a janky user ID field in the Silverlight control).

I handle errors from potentially malicious users by calling a web service. If the user ID variable is invalid, I call this web service like so:

      MyServiceClient WebService = new  MyServiceClient();
      WebService.ErrorHandlerCompleted += new EventHandler< MyLService.ErrorHandlingCompletedEventArgs>(ErrorLog_Completed);
      WebService.ErrorHandlingAsync("Invalid user ID sent",  "0.0.0.0");

BTW, the ErrorLog_Completed method is empty – it’s just there because Silverlight requires it be there.

Which calls the web service in my web project:

        [OperationContract]
        public bool ErrorHandling(string ErrorMessage, sstring IpAddress)
        {
            Data.ErrorHandling(ErrorMessage,  IpAddress);
            return true;
        }

The abbreviated error handling routing then takes, among other things, the IP Address sent from the Silverlight code. If the address sent is 0.0.0.0, then the Request.UserHostAddress method is called to get the honest-to-goodness IP Address. Remember to import the System.Web namespace.

public static bool ErrorHandling(string ErrorMessage, string IpAddress)
        if (IpAddress == "0.0.0.0")
        {
            IpAddress = HttpContext.Current.Request.UserHostAddress;
        }
// Do database stuff here.

Not too tough, but a useful trick if you need the IP address. If you have a better way, please let me know  – I’m always interested in improving my code.

Leave a comment

Creating a Silverlight – WPF Button in code behind

In WPF or Silverlight, to add a Button from code behind insted of in XAML, first make sure the content control has a Children property. For example, I could not add to the SearchPanel Border control in the code below because it lacks such a property.

<Border Name="SearchPanel" CornerRadius="10" BorderBrush="Black" BorderThickness="1">
     <StackPanel Name="SearchStackPanel" />
</Border>

Why’s that? Border inherits from System.Windows.FrameworkElement, which lacks, you guessed it, the Children property. However, StackPanel inherits from System.Windows.Controls.Panel, which does have it.

Now, to actually add the button:

Button RandomButton = new Button();
RandomButton.Name = "RandomButton";
RandomButton.Content = "Random Location";
RandomButton.Click += new RoutedEventHandler(RandomButton_Click);
RandomButton.Height = 25.0;
RandomButton.Width = 100.0;
SearchStackPanel.Children.Add(RandomButton);
private void Random_Click(object sender, RoutedEventArgs e)
{
     // Stuff
}

Leave a comment

Using a JavaScript onLoad event with an ASP.NET Master Page

My site uses a Master Page, and I wanted to run a JavaScript function when my page loaded from one of my content pages. But, as you may have noticed, there is no body tag, so there is no place to put the onLoad property.

After some research, I found two links that looked promising – http://geekswithblogs.net/AzamSharp/archive/2006/04/25/76390.aspx and http://forums.asp.net/p/1310519/2584110.aspx. Both seemed like they would do the job.

But, neither one would actually fire my JS function when the page loaded. Both solutions would work if I hit F5 to refresh the browser, but that was not what I wanted. What to do?

Instead, I found this very simple solution. In the content page, I added this code in the header area,

    <script type="text/javascript">
        function giveFocus() {
            var firstField = document.getElementById('ContentPlaceHolder1_txtUserName');
            firstField.focus();
        }
        window.onload = giveFocus;
    </script>

That was it. I’m not sure why the other two solutions didn’t work, so if anyone has insight, I would like to know.

1 Comment

Shadow and glow effects in Silverlight

I was looking around for how to create a shadow effect for a Border object in Silverlight. I found Pete Brown’s blog, which made my job very easy. Since I had dark backgrounds, I wanted a white shadow. Simply adding a DropShadowEffect to the Border did the trick:

 <Border>
            <Border.Effect>
               <DropShadowEffect BlurRadius="10" Color="White"  Opacity="0.75" Direction="300" />
           </Border.Effect>
</Border>

 If you are looking for a glow effect, where the entire border is surrounding by the shadow effect inside of just having it in one area, set the Direction property to 0:

 <DropShadowEffect x:Key="BorderShadowStyle" BlurRadius="30" Color="White" Opacity="1" Direction="0" ShadowDepth="0" />

 But what if you have lots of Borders that you want to add this effect to? Then you put it into the App.xaml page, of course:

 <Application xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
             xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
            x:Class="Testing.App">
    <Application.Resources>
        <DropShadowEffect x:Key="BorderShadowStyle" BlurRadius="10" Color="White"  Opacity="0.75" Direction="300" />
    </Application.Resources>
</Application>

 Then, when creating new Border objects, you simply set the Effect property to the name you defined in the App.xaml file.

 <Border Effect="{StaticResource BorderShadowStyle}"></Border>

 But watch the performance! I added a glow effect to a dozen different Borders with no problems, but added it to one more and the system slowed down significantly when displaying that particular Border and the controls within. Removing that particular glow effect brought the performance back to normal.

References:

  http://10rem.net/blog/2009/03/18/silverlight-3-%E2%80%93-drop-shadows-and-glows-with-pixel-shaders

 http://msdn.microsoft.com/en-us/library/system.windows.media.effects.dropshadoweffect(VS.95).aspx

1 Comment

Visual Studio 2010 code reuse tips

It’s tip day. Not like this will be a regular thing, but I found these two items handy.

First is creating snippets for VS 2010. You know, of course, that you can right click inside the editor window of Visual Studio and select Insert Snippet to easily insert all kinds of goodness into your code.

You can also create your own snippets if you find yourself writing the same type of code over and over again. I found a concise tutorial on http://www.visualstudiotutor.com/2010/02/create-snippet-visual-studio-2010/ on just how to do this.

In a similar vein of improving development, you can also drag and drop text from the editor window onto the Toolbox. Once there, you can easily drag that code from the Toolbox and into your code.

First, pin the Toolbox so it’s open, then expand the General tab. Then, just highlight the section of code you previously added and drag it onto the General section.

And you can also rename those sections of code dragged onto the Toolbox by right clicking on the code block and selecting Rename. I would suggest doing that, because otherwise it looks ugly and semi-indecipherable.

I found dotnetslackers.com has a visual version of what I just wrote, if you’d like some screenshots. It’s very easy, and especially useful if you are going to give a presentation or lunch and learn.

Leave a comment

Storing a password-mode TextBox value after postback

You know those annoying times when you fill out a large form, submit it, and a post back to the server is performed. But, horror of horrors, you made a mistake, and the page prompts you to make a correction, but the password (or credit card number or whatever) field was cleared! I hate that.

I had an instance where I was that annoyance, and it was keeping me up at night, tossing and turning, worrying what I could do to solve that issue. (That’s sarcasm right there, people.) So after a very brief bit of research, I found this code snippet to fix the problem:

txtPassword.Attributes.Add("value", txtPassword.Text);

Yes, that really is it. I just put that code at the end of my submit button’s click event.

1 Comment

Getting rid of the border around Silverlight HyperLinkButtons

For a Silverlight application, I didn’t want the blue border to appear around a HyperLinkButton when I clicked on it – I wanted a more seamless interface, and I found it with the IsTabStop property.

<HyperlinkButton Name="LikeName" Content="{Binding}" IsTabStop="False" Click="LikeName_Click" Foreground="Black" Height="20" />

The simple change of adding ‘IsTabStop=”False”‘ was all it took.

2 Comments