Thursday, December 30, 2010

Search Youtube Using C#

In this post I want to show you, how to search Youtube with C#, so searching for videos on that platform.
For that we use the Google Data API, especially the Youtube SDK. With these programming libraries  the access to Youtube & Co pretty easy.
The Google Data API can be downloaded on this page, for access on Youtube we only need this file, the Youtube SDK. We need to install it in order to be able to use it.
Searching through Youtube is done with so called feeds. Feeds are something like the content of a webpage in short form, mostly in plain text. In that way, readers can quickly inform themselves of the newest topics, furthermore many programs read these text files (e.g. search engines use them for indexing). This blog has a feed as well.
Using the Youtube SDK we can read feeds with a C# program, for searching on Youtube we use the feed http://gdata.youtube.com/feeds/videos?q=Suchbegriff.
This feed is provided by Youtube and lists the to "Suchbegriff" matching search results in text form, the feed can also be viewed in a browser.

Now I want to explain the code, over which this feed can be analyzed in C#. First the downloaded libraries  Google.GData.Client.dll and Google.GData.Extensions.dll have to be included. They are contained in the Redist folder of the install folder (in my case, C:\Program Files (x86)\Google\Google YouTube SDK for .NET\Redist). Including can be done with Project - Add Reference - Browse. Then the following code includes the needed parts:

using Google.GData.Client;
using Google.GData.Extensions;

Furthermore it is important, to set the target frameproject in project properties correctly - to .Net Framework 4 and not .Net  Framework 4 Client Profile! (Since they dlls were compiled for the first one.)
I think the actual source code is self explaining.
The following console application searches for "VLC einbinden" on Youtube and then prints the first 10 results on the console:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.GData.Client;
using Google.GData.Extensions;

namespace YoutubeToolkit
{
    class YoutubeQuery
    {
        static void Main(string[] args)
        {
            FeedQuery Abfrage = new FeedQuery(); // object for handling feeds
            Abfrage.Uri = new Uri("http://gdata.youtube.com/feeds/videos?q=VLC+einbinden"); // feed URL
            Abfrage.StartIndex = 0; // index, from which on search results should be displayed
            Abfrage.NumberToRetrieve = 10; // maximal number of search results

            Service Service = new Service(); // object to execute the feed query with the FeedQuery Objekt
            AtomFeed Feed = Service.Query(Abfrage); // result of the search query as feed

            // print the title of the video for every search result
            foreach (AtomEntry Ergebnis in Feed.Entries)
            {
                Console.WriteLine(Ergebnis.Title.Text);
            }
        }
    }
}

Monday, December 27, 2010

Disable Sound / Mute Computer

In this post I want to show how to mute the computer. Again, the solution goes over the WinAPI, which is why using System.Runtime.InteropServices; is needed.
The needed P/Invoke function is SendMessageW and has the signature ntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam).
The function sends a message to a specific program or window. To disable the sound in the computer, we send a command to a system process.
The code looks as follows, first the declaration part:

        [DllImport("user32.dll")]
        public static extern IntPtr SendMessageW(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

        private const int APPCOMMAND_VOLUME_MUTE = 0x80000;
        private const int WM_APPCOMMAND = 0x319;

And the function:

private void Mute()
{
    SendMessageW(this.Handle, WM_APPCOMMAND, this.Handle, (IntPtr)APPCOMMAND_VOLUME_MUTE);
}

Tuesday, December 7, 2010

Add Menus and Submenus Dynamically

I devote this post to menu controls in C# and show how to add menus and submenus during runtime, since I got the impression that this is not so clearly understandable.
I show here methods using some extra stuff, so who knows more direct code, please tell me.
Aim of the sample program will be to create the following menu structure:


First we add a control of the type menuStrip to the form using the designer (of course this also can be dynamically, see add controls during runtime).
Now in the form a yet invisible menu bar is created, which is still empty. In the designer you could now write in this bar to add menus, but we focus on the dynamic part.
Super menus, so menus on the highest level in the menu bar (e.g. "Obermenü 1" and "Obermenü 2") can be edited with the property Items of the class menuStrip.




The following code commands create 2 supermenus:

menuStrip1.Items.Add("Obermenü 1");
menuStrip1.Items.Add("Obermenü 2");

Using indicces (e.g. menuStrip1.Items[0]) we can access these menuentries, but we cannot create submenus in them.
For that we have to convert the object explicitely to an object of the type ToolStripMenuItem. This now has the property DropDownItems, with which we can create submenus.
To create the submenus "Untermenü 1" and "Untermenü 2" for example, we run the following code

((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems.Add("Untermenü 1");       
((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems.Add("Untermenü 2");

This submenus right now are not accessible any more. But we need them, if we want to create more submenus, which open to the right (in the example "rechtes Untermenü 1" and "rechtes Untermenü 2").
Therefore, we just save the submenu when creating in a variable of type ToolStripMenuItem, e.g. like this:

ToolStripMenuItem Untermenue1 = (ToolStripMenuItem)((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems.Add("Untermenü 1");

(In front of the assignment again an explicite type conversion has to happen.)
Now we have continous access to the desired submenu, and can add own submenus to it with DropDownItems.Add().
Finally the complete soure code:

            menuStrip1.Items.Add("Obermenü 1");
            menuStrip1.Items.Add("Obermenü 2");

            ToolStripMenuItem Untermenue1 = (ToolStripMenuItem)((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems.Add("Untermenü 1");
            ((ToolStripMenuItem)menuStrip1.Items[0]).DropDownItems.Add("Untermenü 2");

            Untermenue1.DropDownItems.Add("rechtes Untermenü 1");
            Untermenue1.DropDownItems.Add("rechtes Untermenü 2");

Sunday, December 5, 2010

Check Pressing of Multiple Keys Simultaneously

In the functions KeyDown() and KeyPress(), which are implemented by nearly every control, key events can be analyzed.
The argument e of the type KeyEventArgs provides the methods and properties needed for that, for example with e.KeyCode can be checked, which key is pressed.
If multiple keys are pressed (at the same time), for each key an event is triggered, which does not help when wanting to check for key combinations.
In this post I will describe, how to check these cases with they property KeyData and Flags. But, these methods only work when a combination of Alt and / or Shift and / or Ctrl and at most one other key is pressed.
First with KeyData:
In this property 4 bytes are saved, the lower 2 ones represent the pressed key, the upper 2 ones the pressed function keys (Alt, Shift, Ctrl). If multiple keys are pressed, the byte values are combined via Or.
Now when you press a function keys and one other key, a unique bit combination is created. But of course, if multiple "normal" keys are pressed, this uniqueness is not guaranteed anymore, since the bits then can overlap.
To check a pressed combination, the value from e.KeyData is compared to an Or conjunction of the desired value.
The following sample terminates the program, if the key combination Ctrl + Shift + Alt + "E" is pressed:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == (Keys.Shift | Keys.Alt | Keys.Control | Keys.E))
        this.Close();
}

The same result though can also be used if checking the pressed key with e.KeyCode and then checking the properties e.Shift, e.Alt and e.Control (these properties are so called flags, representing the function keys), which describe whether these keys are pressed:

if (e.KeyCode == Keys.E && e.Shift && e.Alt && e.Control)
    this.Close();

Friday, December 3, 2010

Check Status of a Network Adapter

In a previous post was shown how to check if the computer is connected with a network.
In this post now we determine the status of a network interface more exactly. We do not want to distinguish any more only between "connected" and "not connected", but get more information.
Again we use the class System.Net.NetworkInformation, but this time use the property OperationalStatus.
This can have the following values:

  • Dormant - The interface waits for an external event, it cannot transmit data.
  • Down - No connection.
  • LowerLayerDown - The interface cannot transmit data, since it user lower layer interfaces and at least one of them is not working.
  • NotPresent - Not working, mostly due to a hardware failure.
  • Testing - The interface is doing tests.
  • Unknown - Unknown status.
  • Up - The interface is working.

The following small sample lists all network adapters which are working:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (System.Net.NetworkInformation.NetworkInterface n in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
            {
                if (n.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up)
                    Console.WriteLine(n.Name + " is up.");
            }     
        }
    }
}

List All Network Adapters and Show Further Information

As in the previous post we again use the class System.Net.NetworkInformation here. The function  NetworkInterface.GetAllNetworkInterfaces() returns an array of the type System.Net.NetworkInformation.NetworkInterface, in which each entry represents a network interface or network adapter.
We now can iterate over this array and list all network adapters in this way. The following example prints name and status (is explained further in the next post) of each network adapter:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (System.Net.NetworkInformation.NetworkInterface n in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
            {
                Console.WriteLine("Name: " + n.Name + " Status: " + n.OperationalStatus.ToString());
            }
        }
    }
}