Solved

C# WPF URL/TItle from Firefox Swedish letters

Posted on 2013-01-13
7
803 Views
Last Modified: 2013-01-24
I am using this code to get current URL from Firefox

            DdeClient dde = new DdeClient("Firefox", "WWW_GetWindowInfo");
            dde.Connect();
            string url = dde.Request("URL", int.MaxValue);
            dde.Disconnect();

Open in new window


It woks greate, but when entering Swedish website I get problems

Example:
Accessing http://www.binero.se/
The WPF acplication gives me
http://www.binero.se/,Sveriges v?nligaste webbhotell - Binero,

Its supose to be
http://www.binero.se/,Sveriges vänligaste webbhotell - Binero,

How can I solve this so the URL and title can show swedish letters, Å Ä Ö :)
Thanks

Btw if you are going to try this code I recommend installing NDde
http://ndde.codeplex.com/
0
Comment
Question by:chugarah
  • 4
  • 3
7 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38775798
That is an issue with Unicode encoding, and I don't see how you can get around that issue with the DdeClient.  Where are you getting the implementation for DdeClient?
0
 
LVL 1

Author Comment

by:chugarah
ID: 38780673
Yes, I think the same. its wery strange.. Will post the whole code most be something I have done somewhere..?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
using System.IO;
using System.ComponentModel;
using System.Threading;
using System.Collections;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Diagnostics;
using SharpPcap;
using SharpPcap.LibPcap;
using PacketDotNet;
using System.Net.Sockets;
using System.Net;
using NDde.Client;
using System.Text.RegularExpressions;
using WindowsInput;
using System.Net.NetworkInformation;




namespace BrowSerSniffer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summar1y>
    /// 


    public partial class MainWindow : Window
    {

        const int WM_GETTEXT = 0xD;
        public string name;
        public string rawUrl;
        public string urlTitle;
        public string fileStatus;
        public string hostFileActive;


        // Deklarerar bakgrundsabetare
        private readonly BackgroundWorker insaneWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = false };
        private readonly BackgroundWorker insaneWorker2 = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = false };


        // Get a handle to an application window.
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_CLOSE = 0xF060;

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll")]
        static extern byte VkKeyScan(char ch);

        [DllImport("User32.Dll", EntryPoint = "PostMessageA")]
        static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();


        public class BrowserLocation
        {
            /// <summary>
            /// Structure to hold the details regarding a browed location
            /// </summary>
            public struct URLDetails
            {
                /// <summary>
                /// URL (location)
                /// </summary>
                public String URL;

                /// <summary>
                /// Document title
                /// </summary>
                public String Title;
            }

            #region Internet Explorer

            // requires the following DLL added as a reference:
            // C:\Windows\System32\shdocvw.dll

            /// <summary>
            /// Retrieve the current open URLs in Internet Explorer
            /// </summary>
            /// <returns></returns>
            public static URLDetails[] InternetExplorer()
            {
                System.Collections.Generic.List<URLDetails> URLs = new System.Collections.Generic.List<URLDetails>();
                var shellWindows = new SHDocVw.ShellWindows();
                foreach (SHDocVw.InternetExplorer ie in shellWindows)
                    URLs.Add(new URLDetails() { URL = ie.LocationURL, Title = ie.LocationName });
                return URLs.ToArray();
            }

            #endregion

            #region Firefox
            // This requires NDde
            // http://ndde.codeplex.com/

            public static URLDetails[] Firefox()
            {
                NDde.Client.DdeClient dde = new NDde.Client.DdeClient("Firefox", "WWW_GetWindowInfo");
                try
                {
                    dde.Connect();
                    // Title and url is created here, problem is here..anying :P
                    String url = dde.Request("URL", Int32.MaxValue);
                    dde.Disconnect();

                    Int32 stop = url.IndexOf('"', 1);
                    return new URLDetails[]{
                new URLDetails()
                {
                    URL = url.Substring(1, stop - 1),
                    Title = url.Substring(stop + 3, url.Length - stop - 8)
                }
            };
                }
                catch (Exception)
                {
                    return null;
                }
            }
            #endregion
        }


        /******************* Worker HTTP Sniffer ****************/
        private void loadHttpSniffer_Work(object sender, DoWorkEventArgs e)
        {
            // First lets se if Firefox is running
            // Regex 
//            var regex = new Regex(@"(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&amp;%_\./-~-]*)?");
            var regex = new Regex("(?<=(file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)[^/]+");
            int browserCounter = 0;
            while (true)
            {
                Thread.Sleep(1000);
                foreach (Process runningProcess in Process.GetProcesses())
                {
                    var processName = runningProcess.ProcessName;
                    // *** Internet Explorer URL Sniffing ***//

                    try
                    {
                        if (processName == "iexplore")
                        {
                            (new List<BrowserLocation.URLDetails>(BrowserLocation.InternetExplorer())).ForEach(u =>
                            {
                                browserCounter++;
                                urlTitle = u.Title;
                                rawUrl = u.URL;

                                var match = regex.Match(u.URL);

                                if (match.Success)
                                {
                                    name = match.Groups[5].Value;
                                    urlNameListerner = name;
                                }
                            });
                        }
                    }
                    catch (Exception)
                    {
                        Debug.Write("error");
                    }
                    // *** Internet Explorer URL Sniffing ***//



                    // *** Firefox URL Sniffing ***//

                    if (processName == "firefox")
                    {
                        try
                        {
                            (new List<BrowserLocation.URLDetails>(BrowserLocation.Firefox())).ForEach(u =>
                            {
                                browserCounter++;
                                rawUrl = u.URL;
                                // Here is where I get the title
                                urlTitle = u.Title; 

                                var match = regex.Match(u.URL);
                                if (match.Success)
                                {
                                    name = match.Groups[1].Value;
                                    urlNameListerner = name;
                                }
                            });

                        }
                        catch (Exception ex)
                        {
                            Debug.Write("Error Firefox: " + ex);
                        }
                    }
                    // *** Firefox URL Sniffing ***//               
                }
                if (browserCounter <= 0)
                {
                    Console.WriteLine("No browser..sniff");
                    name = null;
                }
            }
        }



        public void startWorkers()
        {
            if (!insaneWorker.IsBusy)
            {
                insaneWorker.DoWork += loadHttpSniffer_Work;
                insaneWorker.RunWorkerAsync();
            }
        }


        private string GetActiveWindowTitle()
        {
            const int nChars = 256;
            IntPtr handle = IntPtr.Zero;
            StringBuilder Buff = new StringBuilder(nChars);
            handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return Buff.ToString();
            }
            return null;
        }


        // Strubg kusterber
        private string _urlNameListerner;
        public string urlNameListerner
        {
            get { return _urlNameListerner; }
            set
            {
                int counter = 0;
                _urlNameListerner = value;

                // Downloading url and scan for bad words
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                WebClient wc = new WebClient();
                byte[] raw = wc.DownloadData(rawUrl);
                string webData = System.Text.Encoding.UTF8.GetString(raw);

                Regex wordFilter = new Regex(@"\b(Sitemap|Legal Documentation|Aftonbladet)\b", RegexOptions.IgnoreCase);
                var matchResults = wordFilter.Match(webData);

                /**** Firefox ****/
                string windowTitle = GetActiveWindowTitle();
                Regex findFirefox = new Regex(@"Mozilla Firefox", RegexOptions.IgnoreCase);
                var matchFirefox = findFirefox.Match(windowTitle);

                // Kontrollerar om anvädaren använder firefox
                if (matchFirefox.Success)
                {
                    // Counting results..boring
                    while (matchResults.Success)
                    {
                        counter++;
                        matchResults = matchResults.NextMatch();
                    }

                    // ´Limiting badwords...bububäbä
                    if (counter > 2)
                    {
                        // An warning box will apear..somewhere
                        Console.WriteLine("Bad URL..Warning");

                        // Send the user to home address
                        InputSimulator.SimulateKeyPress(VirtualKeyCode.BROWSER_HOME);
                    }
                }
                /**** Firefox ****/


                 /**** IE ****/
                 IntPtr ie = FindWindow(null, urlTitle + " - Windows Internet Explorer");
                 IntPtr chrome = FindWindow(null, urlTitle + " - Google Chrome");

                 if (!ie.Equals(IntPtr.Zero))
                 {
                     while (matchResults.Success)
                     {
                         counter++;
                         matchResults = matchResults.NextMatch();
                     }

                     // Limiting bad words agiaan
                     if (counter > 2)
                     {
                         // En varnings ruta skall visas här
                         Console.WriteLine("Bad URL..Warning");

                         // Send the user to home address
                         InputSimulator.SimulateKeyPress(VirtualKeyCode.BROWSER_HOME);
                     }
                 }
                 /**** IE ****/

            }
        }


        public MainWindow()
        {
            InitializeComponent();

            // Start background stuff
            startWorkers(); 
        }
    }
}

Open in new window


I know..its alot :S..but maybe it helps?
Thanks
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38780683
Where are you getting the DdeClient from?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 1

Author Comment

by:chugarah
ID: 38780949
Hmmm?  Well I got it from Visual studio NuGet package manager, just searched for it and downloaded it from there.

NuGet
0
 
LVL 1

Author Comment

by:chugarah
ID: 38780954
The strange thing, it works when using IE but not firefox, tried also to change encoding to something else (in the webbrowser). Its set to Unicode(UTF-8) by default.
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 38783048
I downloaded the source code for the NDde project from CodePlex, and I found that it uses ASCII encoding, and not UTF-8 or Unicode:

http://ndde.codeplex.com/

Public/Advanced/DdeContext:

       private Encoding _Encoding      = Encoding.ASCII; // This is a cached DdemlContext property.

Open in new window

0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 38815906
Were you able to find a solution?
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now