WinForm stuck on a disconnected monitor

Recently, I had a customer report that the application I am writing got stuck off screen, and he couldn’t get at it. This happened by moving the application to his external monitor and then minimizing. After disconnecting the monitor, he would restore the application and it would be positioned off screen (on the now disconnected monitor).

To solve this problem, I just look at all available screens and make sure that the location of the window is inside the working area of one of them. If it is not, I move it to the primary display:

bool visible = false;
foreach (var screen in Screen.AllScreens)
{
    if (screen.WorkingArea.Contains(this.DesktopLocation))
    {
        visible = true;
        break;
    }
}
if (!visible)
    this.Location = new Point(100, 100);
Posted in WinForms | Comments Off on WinForm stuck on a disconnected monitor

P2P with WCF

A couple posts ago I was doing some experimentation with TCPClient and TCPServer. The bulk of my testing was done by creating a simple chat application. After that I decided I wanted to figure out how to do the same thing using WCF. The goal was to have an application that could talk directly with the same application on another computer using WCF.

First I needed a contract:

[ServiceContract(Namespace = "http://WCFTest")]
public interface IChat
{
    [OperationContract(IsOneWay = true)]
    void SendChat(string message);
}

And an implementation of the contract:

public class ChatService : IChat
{
    public static ChatWindow chatWindow;
 
    public void SendChat(string message)
    {
        chatWindow.AppendText(message);
    }
}

The static field is there because every time a request comes in, a new instance of ChatService is created by the host. This is important to note, because with the default behavior you cannot expect state to stick around between requests.

Now I could create a service host and open my chat window:

static void Main()
{
    var window = new ChatWindow();
    ChatService.chatWindow = window;
    try
    {
        host = new ServiceHost(typeof(ChatService));
        host.Open();
    }
    catch (CommunicationException exception)
    {
        window.AppendText(exception.Message);
        host.Abort();
    }
    window.ShowDialog();
}

Next I needed to add the client code:

[ServiceContractAttribute(Namespace = "http://WCFTest", 
    ConfigurationName = "WCFTest.IChatClient")]
public interface IChatClient
{
    [OperationContract(IsOneWay = true, 
        Action = "http://WCFTest/IChat/SendChat")]
    void SendChat(string message);
}
 
public partial class ChatClient 
    : ClientBase<IChatClient>, IChatClient
{
    public ChatClient()
    {
    }
 
    public void SendChat(string message)
    {
        base.Channel.SendChat(message);
    }
}

This allowed my application to create a client, and make calls to the WCF interface:

private void sendButton_Click(object sender, EventArgs e)
{
    var client = new ChatClient();
 
    client.SendChat(chatMessage.Text);
    chatMessage.Text = "";
}

The app.config for this application contains a services and client section, with endpoints defined in both. The client section’s endpoint defines the address of the computer to connect to, but with a little more code it could get addresses for computers dynamically and connect to multiple computers.

In my TCPClient/TCPServer experiment, I was trying to send delegates across the wire. One of the cool thing about WCF is that I wouldn’t need to do that anymore, the contract just needs to define the methods that can be called.

Posted in .Net, C#, Networking, WCF | Comments Off on P2P with WCF

Windows 7 API Code Pack

Jay Wren told me yesterday about the Windows 7 managed API code pack that Microsoft has released. I spent a little bit of time looking at it today, and I’ve got to say that I’m pretty impressed. It provides interop wrappers around many of the Windows 7 (and some Vista) features, including many of the Shell features (taskbar, file system, Start menu, Recycle bin, etc.). It also provides managed access to many of the DirectX 11 features, which I thought was especially cool.

With the download they provide samples and all of the API code. I dove into the DirectX code, and while I don’t know DirectX thoroughly, there are a lot of functions there. The DirectX sample only shows how to use DXGI (DirectX Graphics Infrastructure, provides access to the low level computer details) to enumerate through computer information such as system memory, monitors, and DirectX support, but it looks like could definitely use it to do anything you would want to do in DirectX.

Microsoft’s blog post about it: here.

Posted in .Net, Windows 7 | Comments Off on Windows 7 API Code Pack

A Small TCP Experiment

I’m going to be writing some networking code for a personal project, so I spent some time learning to use TcpClient/TcpListener. After starting to learn them, I thought it might be interesting if I could send a delegate across the wire.

Since I wasn’t quite sure what I’d be sending and receiving when I started learning how to use the TcpClient class, I decided that I would use BinaryFormatter to serialize all of my messages. This meant that I could easily create a class that contained everything I wanted to send. This is where I started my experiment:

[Serializable]
public class InfoToSend
{
    public string Message
    { get; set; }
 
    public delegate void MessageParse(string text);
    public MessageParse MessageParsingMethod
    { get; set; }
}

In my first attempt, I set MessageParsingMethod to a method that was in the WinForm I am using as a GUI for the project. This threw an exception that came from an unintended consequence of trying to serialize a delegate: it also tried to serialize my form, which isn’t serializable.

To get around this limitation, I created a new class that didn’t do exactly what I wanted, but allowed me to demonstrate sending a delegate:

[Serializable]
public class ShowMessageBox
{
    public void YesNo(string message)
    { MessageBox.Show(message, "", MessageBoxButtons.YesNo); }
 
    public void Ok(string message)
    { MessageBox.Show(message); }
}

Setting the MessageParsingMethod in InfoToSend to one of these two methods worked like a charm. The message was sent, and the proper method was called in the receiving instance of the program.

While my experiment worked, it has quite a large limitation: the class that contains any method I want to call must be serializable, and the serialized data of that class will be sent across the wire. This could seriously bloat the amount of data being sent.

My next step is to clone my learning project in WCF to figure out the differences between the two and the merits of each.

Posted in .Net, C#, Networking | Comments Off on A Small TCP Experiment

Writing to a CD

In one of my projects I needed to be able to write data to a CD. I found a great article at code guru that helped me out:
http://www.codeguru.com/csharp/.net/net_general/tipstricks/article.php/c15201

However, I did find one bug in his code. On page three he declares his external functions using the DllImport, here is the bugged one:

public static extern bool
   SHGetPathFromIDList(IntPtr ilPtr, string sPath);

The problem I encountered was that after calling the function, my path string was unchanged.  The best explanation I am able to come up with is that strings behave like value types. I did not pass the string in as a ref or out parameter, so my instance of it doesn’t actually change when changed inside the function.  To fix this I changed the string to a StringBuilder (which is a reference type):

public static extern bool SHGetPathFromIDList(
    IntPtr ilPtr, StringBuilder sPath);

Before I called this function, I just created a StringBuilder with a large capacity and it fixed my problem.

My customer only needed this to work in Windows XP, thankfully, because the way Vista handles CD writing seems to mess up this method.  When testing on a Vista machine either the drive was considered Not Ready or when it went to do the writing the OS thought the disk was full or write protected.

Posted in C# | Comments Off on Writing to a CD

When to use Linq: for/foreach

Many people around the office love Linq, but I haven’t used it much and hadn’t heard about it until I started here. I have written a few Linq queries (Linq to Objects) but don’t use them extensively in my coding. In the last couple of days I have asked a few people what it is that causes them to go: “Oh! I should use Linq here.”  I got replies like:

“I always use Linq.”
“All the time.”

After pushing a bit harder, someone said that Linq replaces for/foreach loops pretty well. Last night I came up with a pretty nice Linq statement after realizing that I was going to write a foreach loop. Now when I go to write “for” I stop and think if Linq would work better.

What key words trigger the “I should use Linq here” reaction in you?

Posted in C#, Linq | 1 Comment

Bitmap from Texture2D

I’m writing a map editor for a 2D XNA game and wanted to use a lot of the same code for displaying the map in the editor and in the actual game.  However, I wanted the ease of use and familiarity of WinForms for the user interface.

My plan was to have a window that would contain buttons for each ground texture that you could paint with.  The background image of each button should represent what texture it will allow you to paint with.  Thus, my problem: I needed to put an image that I had in memory as a Texture2D onto the Button that takes System.Drawing.Image.  Furthermore, to make the editor more flexible, the Texture2D I have in memory contains all of the possible ground tiles, so I need to only put one small portion of it onto the Button.

I searched and was unable to find a great way to do this, so I came up with this:

private Bitmap GetButtonImage(Microsoft.Xna.Framework.Rectangle tile, 
                  Microsoft.Xna.Framework.Graphics.Texture2D tileTex)
{
    int[] data = new int[tile.Width * tile.Height];
    tileTex.GetData<int>(0, tile, data, 0, tile.Width * tile.Height);
    Bitmap bitmap = new Bitmap(tile.Width, tile.Height);
 
    for (int x = 0; x < tile.Width; ++x)
    {
        for (int y = 0; y < tile.Height; ++y)
        {
            Color bitmapColor = 
                Color.FromArgb(data[y * tile.Width + x]);
 
            bitmap.SetPixel(x, y, bitmapColor);
        }
    }
    return bitmap;
}

The method takes in the Rectangle that contains the part of the texture that you want to get as a Bitmap, and the Texture2D that contains all the ground tiles.  It spits out a Bitmap that only contains the part of the texture you wanted.

This could probably be optimized by taking in an array of data, a start index, and an end index so that I only end up calling Texture2D.GetData once, but that would add a bit to the code snippet.

Posted in WinForms, XNA | 2 Comments

7

Well, I’m glad to see that Windows 7 has the blue screen of death that we are all familiar with.  At least some things don’t change, ever.

I was very excited yesterday to get Windows 7 installed on my system. I wiped out one of my partitions and started the install.  Everything went well.  I was able to get logged in, play around with the interface a bit, change the background, normal start up tasks. 

I didn’t even need to install my graphics drivers, and it booted into beautiful 1440×900 resolution.  However, as soon as I installed the drivers for my wireless card, everything came to a screeching halt.

The wireless card is sitting in one of my PCI slots, and the graphics card is in a PCI-E slot.  When I disable the wireless card, or don’t try to send any traffic across it, the system works just fine.  As soon as I connect to an access point and start sending significant amounts of data across it: Blue Screen!  I’m guessing that it is an artifact from Vista: http://support.microsoft.com/KB/952681.

If you start blue screening in 7, you might want to check to see what you have in your PCI slots, and if something isn’t necessary disable it (or take it out of the computer).  I had an interesting thing happen with the wireless card disabled in the hardware profiles: my video card had really bad performance.  Video became very jittery.

I enjoyed the short time I’ve spent with 7, but not being able to access the Internet restricts what I can do with it.  I’m thinking I might move my computer closer to my router to connect with a cable, but this can only be a temporary fix.  I don’t think the people I live with would like me clutter the house with my computers!  There is a bug report in Connect Microsoft for this now.

Posted in BSOD, Windows 7 | Comments Off on 7

CodeMash 2009

Last week I went to my first CodeMash.  It was a lot of fun and quite exhausting.  Since I didn’t have any experience with functional languages before CodeMash I decided to sit in on the talks about Erlang and the functional parts of Scala.  These languages had some pretty cool features; I especially liked the way they handle concurrent programming.  The sender/receiver model is an interesting way to handle the problem, and a lot easier to wrap your mind around.

I didn’t want to talk much about the content of CodeMash in this post, though.  Maybe I should have titled this “Conferences for newbies”:

Selecting sessions
This is not the easiest thing to do when you don’t know what to expect.  The abstract gives some idea about what is going on in each session, but doesn’t tell you all the relevant information.  I chose many of mine, like I said, because I wanted to get some exposure to Functional programming.  I would suggest getting exposure to as much as you can, and this means selecting topics that you know nothing about, even if you don’t see immediate use in it.  Another SRT employee said that he selects sessions by going to the ones that sound the most boring; he learns the most by doing this.
It is also a good idea to try to find out who the really good speakers at the conference are, and go see them.  I went to a session that I was not planning on attending solely because I was told that the speaker was very good.  It turned out to be one of the best sessions I went to, and even though I won’t immediately use the information from it I will have the knowledge for when I do need it. 
Networking
Meet as many people as you can.  There is a lot of value in this.  I failed to do this, and regret it.  These people can teach you more than you can imagine.
Open Spaces
If the conference you are at has open spaces going on, go to one.  If this is your first time to experience an open space event, just walk into a random one.  It doesn’t matter what the topic is, you just need to go in and see it.  The Law of Two Feet says that you should leave if you are not contributing to or gaining anything from the space; however, if it is your first open space, you will gain from just being there and seeing the process.  The biggest thing I regret from this conference is not having gone to  an Open Space.

But, as stated by the rules of Open Spaces: “Whatever happened is the only thing that could have happened”.

Posted in CodeMash, Conferences | Comments Off on CodeMash 2009

Validation controls are pretty cool

I’ve been reading an ASP.Net book lately and just got to the information about Validation controls.  These seem like a pretty sweet way to get a lot done with very little code.  For example, say a that I want a text field that is required, all I have to do is add:

<asp:RequiredFieldValidator ID="reqNum" runat="server"  
    ControlToValidate="txtUser" Text="Number is required"/> 

This will perform a validation on a control named “txtUser” making sure that it has a value.  This is all I have to do to get both client-side Javascript validation and server-side validation.  Both of these validations will fire, so if the user has Javascript disabled in their browser, the server-side validation will still happen.  However, be fore warned that the pages is posted and the click event will fire, regardless of whether or not the input is valid.  There is a property of the Page class called IsValid that is set to false if a validation control has failed.  This means that your button’s click function should look something like this:

if (Page.IsValid)
{ doStuff(); }

The RequiredFieldValidator also has an initial value as a property, and will fail if the field is still that initial value.  This is especially useful with Drop Downs that you want to make sure that the user has selected a value in:

Region: <asp:DropDownList ID="lstRegion" runat="server">
         <asp:ListItem Value="0" Selected="True">Choose a region
         </asp:ListItem>
         <asp:ListItem Value="1">East</asp:ListItem>
         <asp:ListItem Value="2">West</asp:ListItem>
        </asp:DropDownList>
<asp:RequiredFieldValidator ID="reqRegion" runat="server" 
 ControlToValidate="lstRegion" Text="Choose a region" InitialValue="0"/>

Now if the user does not change the value of the Drop Down, the validation will fail.

There are three other built in validators and you can create custom validators.  The custom validators can have a client-side validation function written in JavaScript or VBScript, but they should always have a server-side function tied to OnServerValidate in case the user has scripts turned off in the browser.  There is a lot to be said about validation controls, but I’d like to mention a couple other things I found interesting.

You can use one CompareValidator to validate the value and type of a field.  Setting the Operator to something besides “DataTypeCheck” and setting the Type property will both make sure the value fulfills the comparison and is of the right type.  For example, if you wanted the user to input an integer greater than 0, you could use the following validation control:

<asp:CompareValidator ID="compNumber" runat="server" 
 ControlToValidate="txtNumber" Text="Must be an integer greater than 0" 
 Type="Integer" Operator="GreaterThan" ValueToCompare="0"/>

Another thing to note is that by default these validation controls will take up the space on the page required by the value of the Text property.  Setting the Display property to “Dynamic” will make them only take up space if the message is visible.  If you plan on having multiple validations on the same control, you should make the Display=”Dynamic” so that you don’t end up with strange looking blank spots.

Here’s the plug: I’ve been reading “Core Internet Application Development with ASP.Net 2.0” by Randy Connolly.  I’ve found it quite good so far.

Posted in ASP.Net, Web programming | Comments Off on Validation controls are pretty cool