воскресенье, 12 сентября 2010 г.

How to Convert image to string in PHP



I have been looking to send the output from GD to a text string without proxying via a file or to a browser.

I have come up with a solution.

This code buffers the output between the ob_start() and ob_end() functions into ob_get_contents()



See the example below

<?php
// Create a test source image for this example
$im imagecreatetruecolor(30050);
$text_color imagecolorallocate($im2331491);
imagestring($im155,  'A Simple Text String'$text_color);

// start buffering
ob_start();
// output jpeg (or any other chosen) format & quality
imagejpeg($imNULL85);
// capture output to string
$contents ob_get_contents();
// end capture
ob_end_clean();

// be tidy; free up memory
imagedestroy($im);

// lastly (for the example) we are writing the string to a file
$fh fopen("./temp/img.jpg""a+" );
    fwrite$fh$contents );
fclose$fh );
?> 

PHP: Sending Email (Text/HTML/Attachments)



Email is the most popular Internet service today. A plenty of emails are sent and delivered each day. The goal of this tutorial is to demonstrate how to generate and send emails in PHP.
So, you want to send automated email messages from your PHP application. This can be in direct response to a user's action, such as signing up for your site, or a recurring event at a set time, such as a monthly newsletter. Sometimes email contains file attachments, both plain text and HTML portions, and so on. To understand how to send each variation that may exist on an email, we will start with the simple example and move to the more complicated.
Note that to send email with PHP you need a working email server that you have permission to use: for Unix machines, this is often Sendmail; for Windows machines, you must set the SMTP directive in your php.ini file to point to your email server.


Sending a Simple Text Email
At first let's consider how to send a simple text email messages. PHP includes the mail() function for sending email, which takes three basic and two optional parameters. These parameters are, in order, the email address to send to, the subject of the email, the message to be sent, additional headers you want to include and finally an additional parameter to the Sendmail program. Themail() function returns True if the message is sent successfully and False otherwise. Have a look at the example:
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email';
//define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail.";
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//send the email$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, it very easy to send an email. You can add more receivers by either adding their addresses, comma separated, to the $to variable, or by adding cc: or bcc: headers. If you don't receive the test mail, you have probably installed PHP incorrectly, or may not have permission to send emails.
Sending HTML Email
The next step is to examine how to send HTML email. However, some mail clients cannot understand HTML emails. Therefore it is best to send any HTML email using a multipart construction, where one part contains a plain-text version of the email and the other part is HTML. If your customers have HTML email turned off, they will still get a nice email, even if they don't get all of the HTML markup. Have a look at the example:
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.ob_start(); //Turn on output buffering
?>
--PHP-alt-
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!


This is something with HTML formatting.


--PHP-alt---
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
In the preceding example we add one additional header of Content-type:multipart/alternative and boundary string that marks the different areas of the email. Note that the content type of the message itself is sent as a mail header, while the content types of the individual parts of the message are embedded in the message itself. This way, mail clients can decide which part of the message they want to display.
Sending Email with Attachment
The last variation that we will consider is email with attachments. To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email. Have a look at the example:
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash

$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks

$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-
Content-Type: multipart/alternative; boundary="PHP-alt-"

--PHP-alt-
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!


This is something with HTML formatting.


--PHP-alt---

--PHP-mixed-
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment


--PHP-mixed---

//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64,  split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.

вторник, 7 сентября 2010 г.

WPF OpenFileDialog() locks the folder




I use OpenFileDialog() in my Silverlight application. When I select a file using ShowDialog() it simply locks the file until I close my application.
I am not able to rename or delete the folder when the application is running (silverlight application in browser)
If I try to select any other file in any another folder, I am able to rename the previous folder. It seems it is releasing the handle.
My goal: I want to rename/delete the folder in filesystem (manually) once I finished uploading.




By default the dialog changes the process' current directory (as in System.Environment.CurrentDirectory) to the one the selected file is in. This is so it can default to the same directory again if you open the dialog a second time.It's not the dialog itself that keeps the directory "locked", it's the fact that it's the current directory for the process. Anyway, you can suppress this behavior by setting the dialog's RestoreDirectory property to true.

воскресенье, 5 сентября 2010 г.

How to connect to MySQL via C# .Net and the MySql Connector/Net



This article and tutorial describes and demonstrates how you can connect to MySQL in a c# application.
  • First, you need to install the mysql connector/net, it is located at: http://dev.mysql.com/downloads/connector/net/
  • Next create a new project
  • Next add reference to: MySql.Data
  • Next add "using MySql.Data.MySqlClient;"
  • Finally add the following code to your application:


private void button1_Click(object sender, System.EventArgs e)
  {
   string MyConString = "SERVER=localhost;" +
    "DATABASE=mydatabase;" +
    "UID=testuser;" +
    "PASSWORD=testpassword;";
   MySqlConnection connection = new MySqlConnection(MyConString);
   MySqlCommand command = connection.CreateCommand();
   MySqlDataReader Reader;
   command.CommandText = "select * from mycustomers";
   connection.Open();
   Reader = command.ExecuteReader();
   while (Reader.Read())
   {
    string thisrow = "";
    for (int i= 0;i
      thisrow+=Reader.GetValue(i).ToString() + ",";
    listBox1.Items.Add(thisrow);
   }
   connection.Close();
  }

пятница, 3 сентября 2010 г.

How do make modal dialog in WPF?



message box is a dialog box that can be used to display textual information and to allow users to make decisions with buttons. The following figure shows a message box that displays textual information, asks a question, and provides the user with three buttons to answer the question.
Word Processor dialog box
To create a message box, you use the MessageBox class. MessageBox lets you configure the message box text, title, icon, and buttons, using code like the following.

// Configure the message box to be displayed
string messageBoxText = "Do you want to save changes?";
string caption = "Word Processor";
MessageBoxButton button = MessageBoxButton.YesNoCancel;
MessageBoxImage icon = MessageBoxImage.Warning;
To show a message box, you call the static Show method, as demonstrated in the following code.

// Display message box
MessageBox.Show(messageBoxText, caption, button, icon);
When code that shows a message box needs to detect and process the user's decision (which button was pressed), the code can inspect the message box result, as shown in the following code.

// Display message box
MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);

// Process message box results
switch (result)
{
    case MessageBoxResult.Yes:
        // User pressed Yes button
        // ...
        break;
    case MessageBoxResult.No:
        // User pressed No button
        // ...
        break;
    case MessageBoxResult.Cancel:
        // User pressed Cancel button
        // ...
        break;
}


For more information on using message boxes, see MessageBoxMessageBox Sample, and Dialog Box Sample
Source: http://msdn.microsoft.com/en-us/library/aa969773.aspx

How to exit a WPF app programmatically?



To exit your application you can call
Application.Current.Shutdown();
As described in the documentation to the Application.Shutdown method you can also modify the shutdown behavior of your application by specifying a ShutdownMode:


Shutdown is implicitly called by Windows Presentation Foundation (WPF) in the following situations:
  • When ShutdownMode is set to OnLastWindowClose.
  • When the ShutdownMode is set to OnMainWindowClose.
  • When a user ends a session and the SessionEnding event is either unhandled, or handled without cancellation.
Please also note that Application.Current.Shutdown(); may only be called from the thread that created the Application object, i.e. normally the main thread.

How To Check Internet Connection With C#



I wrote a small application which uploads Images of new products and therefore I had to check if the Internet Connection State is active, otherwise it would crash. There are actually two ways (and probably more) of doing this, depending on your system. You could go with a direct api call:

        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

        //Creating a function that uses the API function...
        public static bool IsConnectedToInternet()
        {
            int Desc;
            return InternetGetConnectedState(out Desc, 0);
        }

The Description can be found on MSDN, depending on the Connection the proper Value has to be entered.


Another way would be resolving some host of which you are sure it is online all the time. That could be microsoft.com, your company’s website or something else. Here we go:

        public static bool IsConnected()
        {
            System.Uri Url = new System.Uri("http://www.microsoft.com");

            System.Net.WebRequest WebReq;
            System.Net.WebResponse Resp;
            WebReq = System.Net.WebRequest.Create(Url);            

            try
            {
                Resp = WebReq.GetResponse();
                Resp.Close();
                WebReq = null;
                return true;
            }

            catch
            {
                WebReq = null;
                return false;
            }
        }

Include one of those functions in your code and you’re set!