Thursday, July 24, 2014

Check if Antivirus Software Installed

Today I want to show, how to check with C#, whether some Antivirus software is installed. We do this using a WMI query, in the linked post I gave a little introduction to that topic.
The path needed for this is root/SecurityCenter2/AntiVirusProduct, the query then returns for every installed Antivirus product an object with some attributes, amongst others of course name, product state, path to the executable and date (displayName, productState, pathToSignedProductExe und timestamp).
In the post linked above I also wrote about the WMI Object Browser, with which the WMI can be browsed and which explains the meaning of some attributes and classes. For the class used here unfortunately no explanation is existing though, online there is no real information as well.
For example I do not know, what timestamp is supposed to be, about the meaning of productState you here find a nice theory. I would appreciate hints and explanations a lot.
Our main goal though, the simply request whether an Antivirus program is installed and if yes, which, is reached, the code:
            ManagementObjectSearcher MySearcher =
               new ManagementObjectSearcher("root\\SecurityCenter2", "SELECT * FROM " + "AntiVirusProduct");

            string Result = "";

            foreach (ManagementObject queryObj in MySearcher.Get())
                Result += "New Product:" + Environment.NewLine;
                foreach (PropertyData propertyData in queryObj.Properties)
                    Result += propertyData.Name.ToString() + ":" + propertyData.Value.ToString() + Environment.NewLine;

Wednesday, July 23, 2014

Use WMI Management Tools (especially the WMI Browser)

WMI means Windows Management Instrumentation, with it locally or via network one can access nearly all settings of a computer, either for reading or writing
When programming with C# we can also use it and with it read out or manage interesting system settings, for example creating a system restore point.
This post is not about .Net programming but about the usage of the WMI Administrative Tools, more precisely about the usage of the Object Browser contained in it.
As the name already says, with these tools designed by Microsoft the WMI can be managed, information about available classes etc. can be accessed.
For us programmiers probably the WMI Object Browser is interesting. With it the namespaces and classes of the WMI can be browsed, partially also some more detailed information about purpose and usage of them is displayed - which is very useful, for example if we want to read out some property and do not know what the attributes mean.
Since one has to pay attention to certain things for getting the browser to run, I here want to post a quick guide (Remark: My Windows is running in German, therefore the images show the German interface. I hope you still can get what I mean):

  • First you have to open the file "browser.htm" from the WMI Tools folder with the Internet Explorer  as Administrator, in my case the path is C:\Program Files (x86)\WMI Tools\browser.htm. The execution of blocked content has to be allowed.
  • With current IE versions the browser does not work, therefore we have to chose IE  7 as compatibility mode.  For that we press F12 and and select (Internet Explorer 7) in Document Mode and User-Agent.

  • Then some window should pop, in which you can connect to a namespace.

  • Eventually when you are connected you should get to see a window like this, in which then, like described before, the available classes etc. are listed.

Sunday, July 13, 2014

Post (Fake) Position Via Facebook

After the previous two preparing posts I today want to show, how one can post his position via Facebook, but use any arbitrary place as this.
We use the code of the post publish Facebook posts, and append the data submitted there with the parameter place. With this we can specify our (alleged) position, so that then "in X" is written below the post.
As place we can either, like describe here under Tagging Places, enter the URL of an external Open Graph Object with a position, or the ID of a Facebook page. How you can search places via Facebook an thus get their needed ID, I explained in the previous post.
Thus the following code leads to the following result:

            string URL;
            URL = "";

            WebRequest MyRequest;
            MyRequest = WebRequest.Create(URL);
            MyRequest.Method = "POST";

            Stream DataStream = MyRequest.GetRequestStream();

            Byte[] Data = Encoding.UTF8.GetBytes("access_token=ACCESS_TOKEN&message=Getting ready for the game. Go Germany! But may the better win, good luck.&place=110346955653479");

            DataStream.Write(Data, 0, Data.Length);


Saturday, July 12, 2014

Find Places Using Facebook

In this post I want to show, how to perform search queries using the Facebook API, especally for locactions (places). The principle is the same as for the general reading of data from Facebook, only we here use the search function. Because of this reason we also need, as opposed to the sample program of the previous post, a user acces token. How to get one, you can read in the linked post.
When searching for places there are then multiple possibilities, I will present 2 here: Search by coordinates or by keywords.
To look for places next to specific coordinates, the following query is needed: &type=place&center=LATITUDE,LONGITUDE &distance=DISTANCE"

Here the placeholders in capital letters have to be replaced by the correct values. Latitude and longitude have to be submitted in decimal notation (with a decimal dot), positive values represent North and East, negative ones South and West. So is for example (37° 27′ N, 122° 11′ W) = 37.27, -122.11.
Via the parameter distance the distance from the coordinates in meters can be expressed, up to which locations shall be checked.

To search for keywords we use &type=place &q=KEYWORDS

Via the parameter q keywords can be submitted which describe the place, for example parts of the name, the city in which it is located etc.

Of course both queries can be executed as always in the browser too, or we use a HTTP request in C#, what we want to do here.
Before showing the code we first have to talk about the output format.
If you perform the query in the browser, you get the following result:

   "data": [
         "category": "Club",
         "category_list": [
               "id": "354275401259620",
               "name": "Nightlife"
         "location": {
            "street": "Liebigstra\u00dfe 19",
            "city": "Aachen",
            "state": "",
            "country": "Germany",
            "zip": "52070",
            "latitude": 50.789739317735,
            "longitude": 6.1094749147791
         "name": "",
         "id": "106940009344240"

The result is given in the JSON format, which stands for JavaScript Object Notation and is an easy textformat for data exchange.
To be able to interpret the format in C# we use Json.Net, which can be downloaded here. Afterwards we have to add a reference in our projet to the Newtonsoft.Json.dll, which is located in the BIN folder of the installation and then the folder of the corresponding .Net version.
The following program looks for places close to the given coordinates and prints ID, name etc in a textbox:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;

namespace FacebookSearch
    public partial class Form1 : Form
        public Form1()

        private void Form1_Load(object sender, EventArgs e)
            string RequestURL;
            RequestURL = "" +

            // using Keywords:
            // RequestURL = "";

            WebRequest GetRequest;
            GetRequest = WebRequest.Create(RequestURL);

            Stream ResponseStream;
            ResponseStream = GetRequest.GetResponse().GetResponseStream();
            StreamReader ResponseReader = new StreamReader(ResponseStream);

            string TempLine = ResponseReader.ReadLine();

            JObject FoundPlaces = JObject.Parse(TempLine);

            foreach (var x in FoundPlaces["data"].Children())
                string CategoryName = "";

                textBox1.Text += "Name:" + x["name"].ToString() + "   ID: " + x["id"] +  "   City: " + x["location"]["city"] + "    Street: " + x["location"]["street"] + Environment.NewLine;


Facebook Access Tokens with Later Expiration Date

In previous posts I wrote about the connection of C# and Facebook (check for that the corresponding label).
In some of those (for example Publish Posts) we needed a so called access token, which grants our application the needed rights. In this post I want to examine these with a little bit more detail, because Facebook shortened the validity of these, they expire after a while.
As you can read hier, there are different kinds of access tokens, e.g. app access tokens and user access tokens. App access tokens are needed for every application which uses Facebook and can simply be acquired by submitting app ID and app secret.
But if one wants to perform user specific actions like the previously mentioned posting of status updates, you need a user access token, which is authorized by the user. With this kind of token we want to deal here.
Token of this kind can be acquired manually via the Graph API Explorer, for which we log on with our desired user account. Then we chose the application we need the token for in the dropdown list above and click "Get Access Token". In the new window we chose the needed permissions and confirm, the token string is then displayed in the textfield. This string we can now use in the program code and with that, for example, post stuff.
In previous posts I with that let the topic rest, since the tokens were valid for a pretty long time. Facebook though now changed this, tokens are now only valid for 1 - 2 hours. The expiration date and other information can be checked with the Facebook Debugger.

If we now write an application which works with Facebook, we have to request a new token manually every 1 - 2 hours. Of course this is not feasible. Since the creation of a token via code is not so easy, I chose the following variant: We once create another token out of the one created above, which is significantly longer valid and pass this to the application.
Regarding this topic here there is a help page of Facebook, in which multiple alternatives are proposed, we use the fourth. As described there, the calling of the following address in the browser leads to the creation of a new access token, which is then displayed:
In this call APP_ID has to be replaced by the app ID, APP_SECRET by the app secret and EXISTING_ACCESS_TOKEN by the short lived token created above. The token created in this way then has a validity of about 2 months.