marți, 6 decembrie 2011

C# Save image from HTML page in WebBrowser control

So you have a C# windows application, a WebBrowser control inside it, and once you navigated to a webpage, you want to save the images inside the loaded HTML webpage.

The best solution I found here: http://stackoverflow.com/questions/2566898/save-images-in-webbrowser-control-without-redownloading-them-from-the-internet/8397454#8397454

The main ideas are:

- Add a reference in your project to Microsoft.mshtml (Project -> Add reference -> GAC -> Microsoft.mshtml).

- Add a 'using' statement at the top of your .cs program:

using mshtml;

- Use the following code to save all images in the HTML document

  IHTMLDocument2 doc = (IHTMLDocument2)WebBrowser1.Document.DomDocument; // gets the dom document of our object WebBrowser1
  IHTMLControlRange imgRange = (IHTMLControlRange) ((HTMLBody) doc.body).createControlRange(); // setting up the controls so we can copy/paste the HTML image objects

  foreach (IHTMLImgElement img in doc.images) // walk through all the images inside the dom document
  {
    imgRange.add((IHTMLControlElement) img); // set up which image (the current one) we are controlling
    imgRange.execCommand("Copy", false, null); // copy the current controlled image
    using (Bitmap bmp = (Bitmap) Clipboard.GetDataObject().GetData(DataFormats.Bitmap)) // create a bitmap object
    {
      bmp.Save(@"C:\downloadedimages\"+img.nameProp); // save the bitmap object to this path on our harddrive
    }
  }
 

Please note the WebBrowser1 name - you must change this to your WebBrowser control name.
Also note the path to where the image is saved - some security measures should be taken here against unwanted file names, executables, etc. as well as making sure the path points to the correct location on your hard drive.

This saves the time and network traffic of re-downloading the image again. There is an alternative to get/reconstruct the absolute image source URL, reading again and then writing the contents in a local file. This didn't work for me as i didn't want to download the image again. There are some server setting which also check for an existing session or cookie, or referrer, by which a direct access to the image is prevented, so the alternative may not work.

The current method is fastest, and it's most intuitive, just as you would do it yourself - right click and save the image from any webpage. Of course, if the 'right-click' is not disabled through Javascript or other method, which in our case is bypassed :)




miercuri, 30 noiembrie 2011

MySql .NET connector example

How to connect to a MySQL database using the mysql .NET connector in C#.

Download and install the MySql.Net connector.

Add a reference to it in your project, that is - click on "Project'->'Add reference', on your '.net assembly browser' tab and choose the library, make sure you're adding the 'Assembly' (the type is shown in the window just after you select the file).

And here is sample code from a working program:

using MySql.Data.MySqlClient;

namespace my_namespace_whatever
{
    public partial class MainForm : Form
    { 
        private MySqlConnection MyConn;
        private MySqlCommand MyCom;
        private MySqlDataAdapter MyDR;
        private string ConnStr;

        public MainForm()
        {
            InitializeComponent();
            // now the interesting part
            ConnStr = "SERVER=localhost;DATABASE=my_database;UID=my_user;PWD=my_password;";
            MyConn = new MySqlConnection(ConnStr);
            if (MyConn.State == ConnectionState.Closed)
            {
               MyConn.Open();
            }
            if (MyConn.State != ConnectionState.Open)
            {
                MessageBox.Show("Could not connect");
            }

            // A.S.O

  }
}

system.data.odbc.odbcexception: error [im002] [microsoft][odbc driver manager] data source name not found and no default driver specified

Trying to use MySQL ODBC driver with a C# program to make a connection to the MySQL database.

Downloaded the latest MySQL ODBC 5.1 Driver from mysql's website, yes, the right version (32-bit for my Windows, check your version - you might need the 64-bit one)

Installed driver.

Created DSN in User DSN (control panel->administrative tools->data sources, and NO, it is NOT needed to create the ODBC Data Source in your System DSN or other, just in User DSN).

Yes, entered correct server name, username, password.

Now going to my C# program, at Connection.Open() - i get the following error: system.data.odbc.odbcexception: error [im002] [microsoft][odbc driver manager] data source name not found and no default driver specified

WHAT in God's name is the problem????

I must say that i've installed and used the mysql odbc connector in the past too, and the connection went smoothly then..

Yes, the problem is the connection string. This is what i had:


ConnStr = "DRIVER={MYSQL ODBC 3.51 Driver};SERVER=localhost;DATABASE=my_database;UID=my_username;PWD=my_password;OPTION=1";


Banged head, ripped clothes off, cut veins, and then success: copy and paste the EXACT ODBC driver name, and now i have this:


ConnStr = "DRIVER={MYSQL ODBC 5.1 Driver};SERVER=localhost;DATABASE=my_database;UID=my_username;PWD=my_password;OPTION=1";


Please notice the string at 'driver=', it must be the same as the ODBC Driver Name, in my case: MYSQL ODBC 5.1 Driver

You find the driver name under Control Panel -> Administrative Tools -> Data Sources (ODBC) , in the 'driver' column (obvious, eh?), next to my own MySQL ODBC Data Source.

Pheewww, that was a bugger.

PS: Oh, and NO, you don't need to add any references to the mysql library either in your project. This is the ODBC method, and you are not using any mysql objects/references here. You must include though your System.Data. If you want to go the mysql .net connection method, search for another post.

luni, 28 noiembrie 2011

Responsive design

WTF is 'responsive design'?
In my search for an answer i've bumped across this page, which pretty much says it all:
http://designmodo.com/responsive-design-examples/

marți, 15 noiembrie 2011

Javascript URL regex

Here's how i check and replace URL patterns in Javascript, with this neat URL regexp pattern:


var URL3_pat = /http:\/\/([\w\d\.\-]+)\.([a-z]{2,8})(($)|([\/\?\#]+$)|(([\/\?\#]+[\w\d\:\@\%\/\;\~\_\?\\\+\-\=\\\\\.\&\,]+)))/m;

r = t.replace(URL3_pat, '<a href="$&" target="out">$&</a>');


Huh? what do you think about this regular expression?

vineri, 28 octombrie 2011

TinyMCE add content - add HTML

Here's the plain simple method to insert some HTML into your tinyMCE *textarea*



html = '<br><br><a href="gourl"><img src="someimageurl" border=0 alt=""></a>';
document.getElementById('#elm1').tinymce().execCommand('mceInsertContent',false,html);


Where id_blog_body is your textarea's ID attribute.


<textarea id="elm1" class="tinymce"></textarea>