.NET & JQuery Tips and Tricks

Icon Causes Dot Net to Crash on XP

In .net on October 10, 2011 at 11:07 am

Or: But it is working on my computer!

 

Well, every developer knows that you should never use that excuse. The fact that it is working on your computer, does not count if it does not on the client PC.

The symptom:

You develop an unbelviable application. You test it and it works fine. Now, you want to make it cool! You find a nice image and want to make an icon out of it.

Now, there are several sizes that are needed. You need a small icon for the title. Usually it is 16 x 16 pixels. But hey, if you’ll create such a small icon, you’ll get it in the task bar at the same size, which is tiny and would be pixelized – not so elegant. So you have to create it bigger 32 x 32 pixels. But then again, you would like to use the icon as the icon of the program, when your user creates a short cut to it on his desktop. Furthermore, if you use windows 7, the icon in the status bar should be even bigger…

Take a breath… Create only one icon, create it big, create it as BIG as you can! I said to myself. I will create a 256 x 256 pixels icon, which will fit to all of my needs. And I did. I created a nice 256 x 256 pixels icon and used it for the title icon, for the task bar icon and for the program icon. I ran my code, oh, what a sweet little-medium-big icon.

Now, one click to automatically deploy and publish my program, and that’s it.

Well, not at all. Here the story just begins. One customer says: “It is not working, I can not install your program”. OK, you say to yourself, he does not know to install a program. “Maybe you don’t have the right framework”. That’s it, I can move on to my next project. But then comes  another one and says: “Hey, I tried to install your program and it crashed”. And you, humbly, say in your heart: ”My programs never crash. It worked perfect on my computer”. Oh no! you said the sentence that should never be said!!

Now, we need to start and investigate. First, I found out that the computer that I develop on is Windows 7, and my clients is XP. So what? you ask yourself – a framework is a framework and it should always work. That is why it is a framework! Isn’t it!!

I found a PC that runs win XP and installed my application, and… IT CRASHED!

After playing around and tryind to figure out what is wrong, I finally got it. It seems that there is some kind of a bug in windows XP. Windows XP can not handle an icon which is bigger than 48 x 48 pixels. Windows 7 will handle it with no problems, but windows XP crashes.

So, I rebuilt my icon to be only 48 x 48 pixels, which is enough for the regular display of windows 7, and… IT WORKS.

I hope that I saved someone some time trying to dig into that issue.

Write to The Facebook Wall – Part III

In .net, facebook on August 14, 2011 at 9:48 am

Creating Your Application in VS – Write to the Wall

space here

1. Go to the designer.cs file. Find the WebBrowser control. Go to the end of its auto created code. Start typing: this.fbWebBrowser.Disposed +=. You’ll get an intellisense message to automatically  create the method. Click on TAB 2 times (click fast – or the method will not be created. If it happens – delete and start over). The editor completes the line to: this.fbWebBrowser.Disposed += new System.EventHandler(fbWebBrowser_Disposed); Also, the method to handle the event will be created in the designer.cs. Cut and paste the method into your form cs code. It should look like this:

        void fbWebBrowser_Disposed(object sender, System.EventArgs e)
        {
               throw new System.NotImplementedException();
        }

2. Create a new class, call it Facebook. This class will handle all traffic to Facebook, so your main code will remain clean.

3. We need to use the access code, and use a POST method in order to write on the wall. Here is how the code should look like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace FacebookAutoSubmitter
{
    class Facebook
    {
        StringBuilder postBody;
        public void WriteOnWall(string Access_Code, string Message)
        {
            postBody = new StringBuilder();
            postBody.Append(“message=” + Message);
            // You can add here other staff that can be posted.
           // Look in the Facebook documentation
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(“https://graph.facebook.com/me/feed?access_token=” + Access_Code);
            byte[] send = Encoding.UTF8.GetBytes(postBody.ToString());
            req.Method = “POST”;
            req.ContentLength = send.Length;
            req.ContentType = “application/x-www-form-urlencoded”;
            req.UserAgent = “Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0″;
            Stream dataStream = req.GetRequestStream();
            dataStream.Write(send, 0, send.Length);
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            dataStream = res.GetResponseStream();
            StreamReader readStream = new StreamReader(dataStream);
            string html = readStream.ReadToEnd();
        }
    }
}
 

4. Go back to your main form, and inside the method that deals with the Disposal of the WebBrowser add these 2 lines:

            Facebook fb = new Facebook();
            fb.WriteOnWall(Access_Token, “Hello Facebook”);
 

5. That is it. You are all set. Test the application. Go to your Facebook page and see for yourself – your new auto post – Hello Facebook - should be written on the wall.

Write to The Facebook Wall – Part II

In .net, facebook on August 7, 2011 at 12:43 pm

Creating your application in VS – Get Required Info

Now, writing some code. I was really waiting for that.

1. Open Visual Studio and create a new project. From the available projects types pick a Windows Forms Application. Ha? Windows Forms? Yes, Windows Forms. Facebook uses cookies in order to move from page to page during the process of logging in, and enabling you to get all the codes for submitting to the wall. Some of these cookies are being created only if you are a real browser. Of course, if you would like to make all of that in a Console, using HttpWebRequest and HttpWebResponse go ahead. Try. After you’ll sweat and fail, come back…

2. Welcome back. Trying to write a Console was really frustrating. Wasn’t it. But we are here to make things easy for you. OK. Drug into your form a WebBrowser control. Give it a name – like fbWebBrowser.

3. Change the ScriptErrorsSuppressed to true. That is to avoid any problems if there are script errors in Facebook pages.  True means that all script errors will be ignored, so nothing will stop this Facebook show.

4. Set the Url property to: https://www.facebook.com/dialog/oauth?client_id=******* &redirect_uri=https://www.facebook.com/connect/login_success.html&scope= offline_access. Replace the “*” with the App Id that you copied from the first part of this tutorial (4).

5. Test the program – you should get in the browser a Facebook login page. Stop the program…

6. In the designer, double click on the WebBrowser control. That will open the code and create a method for the DocumentCompleted event. This event fires when the HTML page is fully charged in the browser. We will use this method in order to move throughout the various stages.

7. In order for our code to know exactly in what stage it is, declare an int variable outside the method but inside the class of the form. We will call that variable: reqCounter and set it to zero.

8. After the login page is loaded, we need to programmatically fill the textboxes (Email, Password) and click the button to move on. The textboxes are easy to find since they have a static ID attribute. The button ID is more difficult to find because it changes dynamically. Meaning that every time you load the first page, you’ll get a different ID for the button. So in order to find the button id, we will use a Regex – so you need to add to our code the namespace: System.Text.RegularExpressions. Let the code speak. This is how your code should look like as for now:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace FacebookAutoSubmitter
{
    public partial class Form1 : Form
    {
        int reqCounter = 0;
        public Form1()
        {
            InitializeComponent();
        }
        private void fbWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            reqCounter++;
            switch (reqCounter)
            {
                // Login – allow access
                case 1:
                    fbWebBrowser.Document.GetElementById(“email”).SetAttribute(“value”, “YOUR@EMAIL”);
                    fbWebBrowser.Document.GetElementById(“pass”).SetAttribute(“value”, “PASSWORD”);
                    Regex _buttonID = new Regex(“(?<=uiButtonConfirm.*?for=\”).*?(?=\”)”);
                    string Html = fbWebBrowser.DocumentText;
                    string buttonID = _buttonID.Match(Html).Value;
                    fbWebBrowser.Document.GetElementById(buttonID).InvokeMember(“click”);
                    // After click – Get Code
                    break;
            }
        }
    }
}

9. Try out this code – see that everything is fine. You should get a blank page with one word: Success – which means, that is correct – that you had a success. You had just verified the app by the user – which is you.

10. You think that you got just one word in stage 9, but you got more than that. The query string that came with the page has a nice secret, and that is a code. A code to let you use the app in your account. So we need to put our hands on that code and ask Facebook to get an access code for our app that we can use in order to write on the wall. Facebook wants to make sure, that the app that got a permission from the user – is a verified app. That is case 2 in our code:

case 2:
                    string code = fbWebBrowser.Url.Query.Replace(“?code=”, “”);
                    fbWebBrowser.Url = new System.Uri(“https://graph.facebook.com/oauth/access_token?”
                        + “client_id=” + CLIENT_ID
                        + “&client_secret=” + CLIENT_SECRET
                        + “&code=” + code
                        + “&redirect_uri=https://www.facebook.com/connect/login_success.html”
                        + “&scope=manage_pages”);

                    // After redirecting – Access Code will be in the body of the HTML
                    break;

CLIENT_ID is the App ID and CLIENT_SECRET is the App Secret from stage 4 in part I.

11. Go ahead, test the code. You’ll get a white page, but this time – a long access code will be written in it.

12. And we need this access code. So first, declare a string outside the scope (inside the form class) so we would be able to take the access code outside this method and use it (in part III). We will call that string – Access_Token. Also – we will dispose our WebBrowser. Why? Because disposing a WebBrowser raises an event, and we will use that event in order to start writing on the wall. Only after completing this stage, we will be able to write on the wall, so we will use that event to know that we got there. So, this is case 3:

                // Parse Acces Code  
                case 3:
                    Regex _token = new Regex(“(?<=access_token=).*?(?=<)”);
                    Access_Token = _token.Match(fbWebBrowser.DocumentText).Value;
                    fbWebBrowser.Dispose();
                    break;

13. In the next part, we will actually write to the Facebook wall, Stay tuned, you are almost done…

Follow

Get every new post delivered to your Inbox.