Skip to content
Aug 30 10

Windows Phone 7: Making an HTTP Request

by Dan

Silverlight and the Windows Phone 7 SDK include the standard System.Net packages for making various requests over ftp and http. Making a standard http request in C# involves setting up a number of delegates and asynchronous callbacks for getting http responses and can be a tad complicated. If you simply want to get some xml or html back as a string over http, it’s much easier to use the simpler, more abstract WebClient class. Here’s an example of using the WebClient class to make a request.

public void getResults(string websiteURL)
{
  WebClient c = new WebClient();
  c.DownloadStringAsync(new Uri(websiteURL));
  c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(c_DownloadStringCompleted);
}

void c_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
  lock (this)
  {
    string s = e.Result;
    XmlReader r = XmlReader.Create(new MemoryStream(System.Text.UnicodeEncoding.Unicode.GetBytes(s)));
    // So something with the XML we get back
  }
}

So basically all we do is say download the string and make the action to take when it is completed as c_DownloadStringCompleted event handler. You may want to do something different than place it in an xml reader (in this case the string we are getting back corresponds to a non-xhtml xml file. Enjoy.

Aug 29 10

Windows Phone 7: ListBox Item Horizontal Width Stretch

by Dan

I have spent most of the day today working on a Windows Phone 7 app I hope to have ready for launch this fall / winter. I figured that adoption of the platform and generation of apps is good for all of us as it generates hype for the platform and facilitates development. So I will be sharing all the gotcha’s and particularly frustrating experiences (and there solutions here!).

In WP7, if you try to use a ListBox control, you’ll noticed that child controls do not completely fill the available space of the control. To do this you have to override the style of the ListBox’s ItemContainer, as well as override the template and set the appropriate HorizontalContentAlignment properties.

First, this is what the problem looks like. In blue we have the entire ListBox Control, and in white is the space for an individual item.

The Problem

 

 

problem

As you can see, the ListBoxItem is shown in white and only fits the size of the content. The entire ListBox is shown in red and remains empty. If you increase the size of the text it will stretch to the width. But if we wanted to align the button on the right as its own column we want the text to take up the remaining space and we need the item to fit the width of the control. Then we’d be able to use a Grid control to set the proper alignment.

The Solution

We have to override not only the HorizontalContentAlignment Properties of the ItemContainer but also pass those onto the Template and Container in the Style. This is very unintuitive as you would expect HorizontalContentAlignment to just work.

 <phone:PhoneApplicationPage.Resources>          <Style x:Key="ListBoxItemStyle1" TargetType="ListBoxItem">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="BorderBrush" Value="Transparent"/>
            <Setter Property="Padding" Value="0"/>
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            <Setter Property="HorizontalAlignment" Value="Stretch" />
            <Setter Property="VerticalContentAlignment" Value="Stretch"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border x:Name="LayoutRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
                            <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>      </phone:PhoneApplicationPage.Resources> 

Then apply it to the ListBox:

 <ListBox x:Name="SearchResultsListBox"
                     Grid.Row="0"
                     HorizontalContentAlignment="Stretch"
                     ItemContainerStyle="{StaticResource ListBoxItemStyle1}"
                     ItemsSource="{Binding ElementName=SearchPageControl, Path=QueryHandler.OpenSearchSuggestion.section.items, Mode=OneWay}">  ... 

The Result

solved

As you can see the item wrapped in white stretches the entire width of the ListBox in red.

Conclusions

Although unintuitive this should get the job done. Hopefully Microsoft can make some of these details more straightforward before the final release or in updated versions of .NET.

Aug 28 10

Finding Memory Leaks in .NET Using SOS.dll and Visual Studio

by Dan

Often, after finishing a major feature or wrapping up an application. You are faced with the challenge of tracking down memory leaks. Memory leaks occur when you allocate memory for an object, then lose track of the reference or overwrite the reference to that memory without freeing the memory in your application (essentially losing or “leaking” memory). In the context of C#, a memory leak is different since you don’t typically explicitly free an object you allocate. In C# a memory leak occurs when you allocate an object and then hold onto it without actually intending to. Finding the leak can be extraordinarily difficult in a large application. Luckily, Microsoft provides us with an extension to the debugger which allows us to inspection the code. This is known as SOS.dll (Son of Strike). First, locate the SOS.dll file on your machine. You can do it by opening up a search window on your windows drive or wherever the .NET framework is installed, and searching for SOS.dll:

sossearch

You’ll want the dll which pertains to your version and binary type (in my case I want the path referring to v4.030319 and non-64bit).

Next we’ll open up our application in visual studio and start the debugger.First you need to enable unmanaged debugging. So right click on your project and go to properties. You should see a window similar to the one below. Select debugging and make sure the circled checkbox is enabled:

enabledebug

Run your application and wait until the point you want to check your memory usage. You’ll want to look for the pause button or hit CTRL+BREAK to break the running of your application.

pause

Next, open the immediate window or go to Debug->Windows->Immediate Window to bring it up.

Now, you’ll want to load SOS.dll to access the extensions, we do this with the load command in below:

load

Ok, now we can issue commands to find out information about our system. Type in “!dumpheap” to get a list of all the allocated objects on the heap. Be careful though, you can easily overwhelm your system with output. To summarize and get only the useful information type “!dumpheap –stat”. You see something like this:

dumpheapstat

The columns in order are, method table, number of instances in memory, total size of instances, type.

!dumpheap has a ton of flags. If you use !dump –type System.String, you can get a summary of all heap objects matching the type (in this case, System.String). Not that the method table is not the same as the memory address. Say we wanted to find out what was holding one of the dictionary objects. We could use !dumpheap –mt <methodtable> to get a list of all the objects in that method table. Then used the address provided to use gcroot to give us all the paths to the object in our application.

mt

Notice in this case there is only one object and one memory address. If your method table or type has many addresses it could be difficult to identify or find your target object (in that case try to find the memory address through a parent object with less instances (or preferably, 1). If we use that address we can use the command “!gcroot 02369d30” to find all references the garbage collector knows is keeping the object down. Output will look something like this:

gcroot

Work backwards from the bottom of each trace. It starts with the object in question and moves up the reference tree to a root node for the application. This would tell us that the object directly above our object is another dictionary, then a schema context and eventually a template. You can do this for any object you’d like to trace and see if the garbage collector will cleanup the object.

So whatever is holding onto our object could be causing the leak, therefore we could try to remove the link at the appropriate time, then re-observe to verify its status.

There are many functions available for SOS.dll. For a complete list of functions please visit the MSDN site.

Aug 20 10

HowTo Fix: C# .NET BackgroundWorker.IsBusy Always True

by Dan

BackgroundWorker provides a great simplified mechanism for seperating CPU intensive work from the UI thread in C# .NET. Indeed the MSDN documentation does an excellent job detailing its usage. However, you may come across a bug wherein you need to run the backgroundworker while it is still running. You have code like this:

System.ComponentModel.BackgroundWorker backgroundWorker;
public void someEvent()
{
while (backgroundWorker.IsBusy)
{
Thread.Yield();
}

backgroundWorker.RunWorkerAsync();
}

But you may find that backgroundWorker.IsBusy is always true so the loop never executes. It seems that simply yielding the thread will not force the backgroundWorker to mark itself as done even though that worker thread has successfully completed. In some situations you are blocking the UI so it cannot mark itself complete. To resolve the problem, simply include a call to System.Windows.Forms.Application.DoEvents(). You can do this even if you are running an application under WPF. It should force the UI to load a frame.

using System.Windows.Forms;

System.ComponentModel.BackgroundWorker backgroundWorker;
public void someEvent()
{
while (backgroundWorker.IsBusy)
{
Thread.Yield();
Application.DoEvents();
}

backgroundWorker.RunWorkerAsync();
}

For more information on this method check out the MSDN documentation on Application.DoEvents().

Aug 20 10

Set Operations in .NET C#

by Dan

C# provides access to set methods like Union, Intersect, Difference, etc. These methods are granted to any object adhering to the IEnumerable interface, with one catch. You need to import linq which actually loads the extension granting you those methods. Let’s say you simply open visual studio and load trying to create a list:

Then as you can see we ONLY have access to the IEnumerable default methods like Equals(). However, include using System.Linq; in the top of your file and you get this:

So given these operations you can now take any list and get the Union, Intersection or Difference (among other functional programming capabilities like Map). For more information on Set operations, see the Wikipedia page.