Tuesday, February 26, 2008

Set Label Text in XAML and C#

I made a UI in XAML using the designer... one of the first things I wanted to do was change the text of a Label from C# code. I was surprised to see that in WPF, a Label has no Text property:This is in contrast to a Windows Form, where Label does have a Text property:

Solution:



The answer, of course, is that WPF has a class TextBlock that seems to be a more dynamic version of Label. It has a Text property:


Just as reference, when changing properties of UI components in WPF,


protected void ChangeText(string s)
{
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new TextSetterDelegate(TextSetter), textBlock, s);
}
delegate void TextSetterDelegate(TextBlock tb, string text);
protected void TextSetter(TextBlock tb, string text)
{
tb.Text = text;
}

Wednesday, February 6, 2008

Syntax Highlighting on Blogger

To get nice pretty syntax highlighting on blogger, get google-code-prettify. I also got rid of the blogger bar, though I doubt you're supposed to do that...

Saturday, February 2, 2008

HttpWebRequest with Basic Authentication

It seems like making a web request with basic http authentication in C# should be fairly straight forward.

The Obvious Way:


HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(url);
req.Method = "GET";
req.Credentials = new NetworkCredential(username, password);
req.PreAuthenticate = true;
StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream());

This gives a System.Net.WebException: "The remote server returned an error: (401) Unauthorized.", despite the right username and password.

I also tried using a CredentialCache, to no avail:

HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(url);
req.Method = "GET";
CredentialCache creds = new CredentialCache();
creds.Add(new Uri(url), "basic", new NetworkCredential(username, password));
req.Credentials = creds;
req.PreAuthenticate = true;
StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream());


Looking at the request in Wireshark, we can see that C# simply isn't sending the authorization header. It s eems to me that this facility should be built into the HttpWebRequest class, unless it is and I'm just missing something.






Solution:


I found the solution via http://mark.michaelis.net/Blog/CallingWebServicesUsingBasicAuthentication.aspx. It works to manually set the authorization header header like so:

/* http://mark.michaelis.net/Blog/CallingWebServicesUsingBasicAuthentication.aspx */
byte[] credentialBuffer = new UTF8Encoding().GetBytes(
username + ":" +
password);
req.Headers["Authorization"] =
"Basic " + Convert.ToBase64String(credentialBuffer);

Now it works great. Seems like this should be built into HttpWebRequest to me. There must be a better way to do this?