Purely Technical

NaggieDBCC CHECKDB unable to resolve SQL Database corruption

Thursday, April 22nd, 2010

The logical and physical integrity of all SQL Server database tables is performed by DBCC CHECKDB command. The command performs and divides its operations in three different phases.

The first phase checks the consistency of the allocation structures in disk space, the second phase checks the integrity of all pages and their structures, and the last phase checks the catalog consistency.

If critical errors are found in any of the phases, the DBCC CHECKDB command terminates immediately. This happens when the SQL Server database is badly corrupted, and is beyond the repairing capabilities of DBCC CHECKDB command. In such cases, if you need to access the database records, then you will need to restore the database records from a valid backup. But, if no backup is available or backup falls short to restore the required amount of data, then you will need to repair the database by using advanced MS SQL Server Recovery application.

Let’s consider a practical scenario, where you receive the below error message when you attempt to access one of your table records-

Table error: Object ID O_ID1, index ID I_ID1 cross-object chain linkage. Page P_ID1 points to P_ID2 in object IDO_ID2, index ID I_ID2.

The above error message primarily results in inaccessibility of all the table records. Additionally, the error message pops up every time you attempt to access the table records.

Cause: Reason of error

The above table error message occurs when the next page pointer of P_ID1 page points to different object. This can happen either due to logical corruption factors or physical crash of a system component.

Resolution: Steps to be used to resolve the above error message

Database table corruption, if caused due to physical damage, can be resolved by changing the damaged system component. For logical table corruption reasons, run DBCC CHECKDB command with appropriate repair clause.

While the physical corruption issues can be resolved easily changing the system component, the probability of logical corruption problems being resolved by DBCC CHECKDB command is slightly less. In such cases, you will need to use advanced Recovery application to repair the database table. A SQL Repair software can be easily downloaded from Internet.

Source: www.programmersheaven.com

http://get-a-designer.com

http://www.all1sourcetech.com

Tags: , , , , , ,
Posted in Purely Technical | No Comments »

NaggiePHP Development on the Facebook Platform- Build Your App

Wednesday, April 21st, 2010

Facebook API is very powerful and it allows you to create your own Facebook applications, which you, your friends or everyone else can then consume. You can use the Facebook applications you build on profile pages, canvas pages, and so on. You can even make money by developing practical applications. So, let’s get started with creating your own Facebook application.

What You Need-

To create your own Facebook application, you should know how to program in one of the supported languages, such as PHP, Ruby on Rails, or Python. With that knowledge, all you need to do to get started is:
1. Add Facebook Developer Application to your Facebook account.
Go to the Facebook Developers page and click “Add developer.” This is the central location for all your applications on Facebook. You can request as many as 100 API keys from the applications page, as well as manage and change the settings for all your applications. Now that you have added Facebook Developer Application to your account, let’s move on to adding your very first application.

2. Add your first Facebook application.
Go back to the Facebook Developers page and click the Set Up New Application button. This will take you to the “Create Application” page, where you are required to provide the name of your application and, as a rule, agree to certain terms and conditions.
After saving changes to this page, you will be taken to your application’s homepage, which serves as your application’s edit page. You can change all the settings related to your application here, such as its name, description, icon, logo and much more. You can add more developers if you are going to develop the application in a team.
On the same page, Facebook provides you with an API Key and a Secret Key, which are the passports for your application to interact with

Facebook core applications and the outside world. Do not share you secret key with anyone.

Pre-development Changes

To start developing your application, you need to make important changes to the following settings:

  • API Key – This unique key helps Facebook identify whatever request(s) you make. Enclose this API key along with all your requests.
  • Secret Key – As mentioned previously, you should keep this key safe and share it with no one, because it is responsible for authenticating your request.

Now, click on the Authentication tab, where you need to specify:

  • Post-Authorize Callback URL – When a user authorizes your application and adds it to a Facebook account, then Facebook pings this URL. So, this URL needs to be your site’s URL where you application is hosted. This cannot be a URL from Facebook.
  • Post-Authorize Remove URL – When your application is removed by a user, this URL will be pinged along with a post request, which will contain the User_id. This process allows you to log which user has removed your application.

Now click on the canvas tab, where you need to specify:

  • Canvas Page URL – Choose a canvas page URL for Facebook, such as http://apps.facebook.com/your-app-name.
  • Canvas Callback URL – This is the muscle of your application. Facebook pulls the content from this URL and displays it on the application’s canvas page. The URL can be where you have your application hosted.
  • Render Method – You need to selected this option according to your code. If your code is going to have FBML tags, then you should select “FBML” in this option. Otherwise, leave it default as “iframe” (for this example, you can choose either).

These settings should be enough to get you started with your first Facebook application. Undoubtedly, you can make many other changes to suit your needs in due course.

Now that you have set up the application, let’s have a look-see at how to put some muscle on your bare-bones application. In this example, you need to use Facebook’s PHP client library, which is a compressed file. After downloading the client library, extract the files. You will get two folders namely, footprints and php.

Footprints is a sample application provided to help you understand how the Facebook API works. However, because the API functions keep changing, this code might have some deprecated functions. The php folder contains the library files that you will use to talk back to the Facebook API.

Create a file called index.php and copy the following code into it:

<?php
 require_once 'php/facebook.php';
 $appapikey = 'INPUT YOUR APP KEY HERE';
$appsecret = 'INPUT YOUR APP SECRET KEY HERE';
 //create the object
$facebook = new Facebook($appapikey, $appsecret);
 /**
 * Check if we have an already logged in user ?
 * Yes - Skip the require_login
 * No - User is redirected to facebook login page
 */
if(!is_numeric($facebook->get_loggedin_user()) || !$facebook->api_client->users_hasAppPermission("publish_stream"))
  $facebook->require_login($required_permissions = 'publish_stream');
 /**
 * In case user reaches here and our application doesn't have proper permissions to publish,
 * then display this error message
 */
 if(!$facebook->api_client->users_hasAppPermission("publish_stream"))
{
  echo 'Darn !! Something just broke !!' ;
}
 /**
 * Check if we have Post data and a status to update
 */
if($_POST['update_me'] == 1)
{
    $res=$facebook->api_client->stream_publish($_POST['st'],'');
  $uid = $facebook->get_loggedin_user();
   $tmp = explode ("_",$res);
  if($uid == $tmp[0])
  {
    echo "Timeline updated successfully, <a href='http://www.facebook.com/?id=$uid'> Go back to your profile page</a>";
  }
  else
  {
    echo "Couldn't update your status, Please try again";
  }
}
/**
 * Display the form to update status
 */
else
{
  ?>
 
<form method="POST" action="http://www.your_domain.com/index.php" >
  <input value="1"/>
  <textarea></textarea> <br>
  <input value="Update status" />
 </form>
  <?php
}
?>
Important Tasks to Remember

Make sure you complete the following tasks to properly build your application:

  1. Include the library file (facebook.php) and change the path in require_once to match your folder hierarchy.
  2. Copy/paste the API key and secret key before trying to use your application. It won’t work without these anyhow.
  3. Input the canvas page URL right to the path of the script on your server/domain.

When you execute the above script, it will look for logged in users, if any. If a user is not logged in, then it redirects the user to the Facebook login page. This is also handled by the require_login function, but the problem with require_login is that it redirects so often that any post data to your page is lost. So, you have put a check before calling the require_login function. In the same line, you also check whether or not your application has permission to post updates onto a user’s stream. If you do not have permission, the user is prompted to allow your application.

When you have permissions and post data, the status is updated to the user. When a status is successfully posted, a response of the typeuserid_postid is returned. If it fails, then different error codes are returned. Find a list of error codes on Facebook’s wiki page.

You can extend the above code to suit your requirements. If you feel confident, you can move on to write some advanced programs using FBJS and XFBML. Other than that, you should keep abreast of any functions that Facebook deprecates — particularly those that your code might be using. Otherwise, your application might crash all of a sudden.

Tags: , , , , , ,
Posted in Opensource, Purely Technical | No Comments »

ShwetaHow to Avert and Resolve Oracle Database Corruption

Friday, April 16th, 2010

A database administrator needs to perform various operations like performing incremental backups, identifying and resolving network issues, viewing archive log destination, error generation in alert log, etc. in order to ensure that the database always remains in a running state. However, the possibility of database corruption exists due to human mistakes, virus attacks, and hardware corruption.

Database remains unmountable in most cases after it is corrupted, further rendering to inaccessibility of all its records. In such situations, if the administrator wants to access the Oracle database records, then he/she will need to use a cold backup to restore the database. However, if the administrator has not created any backup or the backup is not sufficient to meet all his/her requirements, then he/she needs to use an advanced third-party Oracle Recovery utility to repair the database.

Let’s consider a practical case, where you, as a database administrator, perform below steps:

1.You copy your database file when your database is alive.
2. Then you update the table stored in the data file.
3. After this, you shutdown the database using ’shutdown immediate’ command and change the datafile with its ‘alive’ copy.

After this, when you try to mount your Oracle database, it does not mount. The reason is-

The fundamental reason for unmountability of the database is corruption in datafile. To prevent the corruption of datafile, you should never follow the above steps sequentially.

Resolution:

It is advisable to restore the database from a standby database in order to resolve datafile corruption and to mount your Oracle database. However, if no such database exists, then you will need to repair the database. To effectively do so, you will need to search for a commercial dbf recovery application that can repair your corrupted database.

A repair tool to recover Oracle database and to bring it back to a reusable state can be easily downloaded from the Internet. Such tools can Recover Oracle Database after any logical corruption scenario using powerful recovery algorithms. Moreover, these tools do not make any change in the original database, making them completely non-destructive in nature.

For most of the Oracle database administrators, Oracle Recovery Software is a utility that they use to recover Oracle database after all kinds of logical crashes. The tool supports recovery of Oracle 9i databases. Designed for Windows XP and 2003, the read only software leaves the original database untouched and unmodified.

Tags: , , , , , ,
Posted in Editorial, Purely Technical | No Comments »

NaggieRemove unprintable or invisible characters from string in VB.net

Monday, April 12th, 2010

This function will help to remove all invisible characters in vb.net string

Public Function Remove(ByVal str As String) As String
        Remove = str
        Dim x As Long
        ' remove all non-printable characters
        While InStr(Remove, vbCrLf) > 0
            Remove = Replace(Remove, vbCrLf, String.Empty)
        End While

        While InStr(Remove, vbTab) > 0
            Remove = Replace(Remove, vbTab, String.Empty)
        End While

        For x = 0 To 31
            While InStr(Remove, Chr(x)) > 0
                Remove = Replace(Remove, Chr(x), String.Empty)
            End While
        Next x

        For x = 127 To 255
            While InStr(Remove, Chr(x)) > 0
                Remove = Replace(Remove, Chr(x), String.Empty)
            End While
        Next x

        'Dim s = New String(" ", 2)
        'While InStr(Remove, s) > 0
        '    Remove = Replace(Remove, s, " ")
        'End While
    End Function

http://www.all1social.com

http://get-a-designer.com

http://www.all1sourcetech.com

Tags: , , , ,
Posted in Purely Technical | No Comments »

NaggieHow to generate readable/remeberable random password?

Saturday, March 27th, 2010

<?php
$randPwd = generatePassword(12);
?>

Fast, simple, and easy way to generate readable/remeberable random password

<?php
//Generates readable/rememberable random password.
function generatePassword($length = 6) {
$chars = array(”a”, “b”, “c”, “d”, “e”, “f”, “g”, “h”, “i”, “j”, “k”, “l”, “m”, “o”, “p”, “r”, “s”, “t”, “u”, “v”, “x”,”y”, “z”);
$vocals = array(”a”, “e”, “i”, “o”, “u”);
$password = “”;
mt_srand ((double) microtime() * 1000000);
for ($i = 1; $i <= $length; $i++)
$password .= ($i % 2 == 0)?$chars[mt_rand(0, count($chars) - 1)]:$vocals[mt_rand(0,count($vocals) - 1)];
return $password;
}
?>
<?php

//Generates readable/rememberable random password.
function generatePassword($length = 6) {
       $chars = 
        array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "o", "p", "r", "s", "t", "u", "v", "x","y", "z");
       $vocals = array("a", "e", "i", "o", "u");
       $password = "";
       mt_srand ((double) microtime() * 1000000);
       for ($i = 1; $i <= $length; $i++)
           $password .= ($i % 2 == 0)?$chars[mt_rand(0, count($chars) - 1)]:$vocals[mt_rand(0,count($vocals) - 1)];
return $password;
}
?>

http://get-a-designer.com

http://www.all1sourcetech.com

Tags: , , ,
Posted in Purely Technical | No Comments »

NaggieInside JSF 2.0’s Ajax and HTTP GET Support

Wednesday, March 17th, 2010

With support for these techniques, this newest version of the Java component UI framework enables developers to build truly dynamic web pages simply and easily.

At the highest level, JSF technology provides an API for creating, managing, and handling UI components and a tag library for using components within a web page. The JSF 2.0 release simplifies the web developer’s life by providing the following:

  • Reusable UI components for easy authoring of web pages
  • Well defined and simple transfer of application data to and from the UI
  • Easy state management across server requests
  • Simplified event handling model
  • Easy creation of custom UI components

For GET requests and Ajax integration, we need to drill down into JSF 2.0’s support, as well as the productive features that this support makes possible. The demo application is an online quiz that allows a registered user to answer five simple questions that test his or her general knowledge. Towards the end of the quiz, the application displays the score.

Using GET Requests in JSF 2.0

To support GET requests, JSF 2.0 introduced the concept of View Parameters. View Parameters provide a way to attach query parameters to URLs. You use the tag <f:viewParam> to specify the query parameters.
Take this code for example:
<f:metadata>
<f:viewParam name=”previousScore” value=”#{recordBean.oldScore}” />
</f:metadata>
In this example, the value of the parameter previousScore will be automatically picked up and pushed into the property oldScore of the recordBean. So, when a request like this comes for a URL:
displayData.jspx?previousScore=10

To support GET requests, JSF 2.0 introduced the concept of View Parameters. View Parameters provide a way to attach query parameters to URLs. You use the tag <f:viewParam> to specify the query parameters.

Take this code for example:

<f:metadata>

<f:viewParam name=”previousScore” value=”#{recordBean.oldScore}” />

</f:metadata>

In this example, the value of the parameter previousScore will be automatically picked up and pushed into the property oldScore of the recordBean. So, when a request like this comes for a URL:

displayData.jspx?previousScore=10

The value of the bean property oldScore will be set to 10 when the request is processed, which avoids manually setting the value or using a listener. Another interesting point to notice is that like any other component the tag <f:viewParam> supports conversion and validation. Hence, there is no need for separate conversion/validation logic.

The new tags in JSF 2.0 related to support for the GETrequest.

h:button :- Renders a button that generates a GET request without any handcoding of URLs

h:link :- Renders a link that generates a GET request without any handcoding of URLs

h:outputStylesheet :- Refers to a CSS resource

h:outputScript :- Refers to a JavaScript resource

f:event :- Registers a specification-defined or a user-defined event

f:ajax :- Enables associated component(s) to make Ajax calls

f:metadata :- Declares the metadata facet for this view

f:viewParam :- Used in to define a view parameter that associates a request parameter to a model property

f:validateBean :- Delegates the validation of the local value to the Bean Validation API

f:validateRegex :- Uses the pattern attribute to validate the wrapping component

f:validateRequired :- Ensures the presence of a value

Bookmarking Support

Because all JSF 1.x interactions with the server use only HTTP POST requests, those JSF versions don’t support bookmarking pages in a web application. Even though some tags supported the construction of URLs, it was a manual process with no support for dynamic URL generation. JSF 2.0’s support for HTTP GET requests provides the bookmarking capability with the help of new renderer kits.

A new UI component UIOutcomeTarget provides properties that you can use to produce a hyperlink at render time. The component allows bookmarking pages for a button or a link.

The two HTML tags that support bookmarking are h:link and h:button. Both generate URLs based on the outcome property of the component, so that the author of the page no longer has to hard code the destination URL. These components use the JSF navigation model to decide the appropriate destination.

Take the following code for example:

<h:link outcome=”login” value=”LoginPage” >

<f:param name=”Login” value=”#{loginBean.uname }” />

</h:link>

This bookmarking feature provides an option for pre-emptive navigation (i.e., the navigation is decided at the render response time before the user has activated the component). This pre-emptive navigation is used to convert the logical outcome of the tag into a physical destination. At render time, the navigation system is consulted to map the outcome to a target view ID, which is then transparently converted into the destination URL. This frees the page author from having to worry about manual URL construction.

Support for Ajax

The default implementation provides a single JavaScript resource that has the resource identifier jsf.js. This resource is required for Ajax, and it must be available under the javax.faces library. The annotation@ResourceDependency is used to specify the Ajax resource for the components, the JavaScript function jsf.ajax.request is used to send information to the server in an asynchronous way, and the JavaScript function jsf.ajax.response is used for sending the information back from the server to the client.

On the client side, the API jsf.ajax.request is used to issue an Ajax request. When the response has to be rendered back to the client, the callback previously provided by jsf.ajax.request is invoked. This automatically updates the client-side DOM to reflect the newly rendered markup.

The two ways to send an Ajax request by registering an event callback function are:

  • Use the JavaScript function jsf.ajax.request
  • Use the <f:ajax> tag

JavaScript Function jsf.ajax.request

The function jsf.ajax.request(source, event, options) is used to send an asynchronous Ajax request to the server. The code snippet below shows how you can use this function:

<commandButton id=”newButton” value=”submit”

onclick=”jsf.ajax.request(this,event,

{execute:’newButton’,render:’status’,onevent: handleEvent,onerror: handleError});return false;”/>

</commandButton/>

The first argument in the function represents the DOM element that made an Ajax call, while the second argument (which is optional) corresponds to the DOM event that triggered this request. The third argument is composed of a set of parameters, which is sent mainly to control the client/server processing. The available options are execute, render, onevent, onerror, and params.

<f:ajax> Tag

JSF 2.0 enables page authoring with <f:ajax>, which is a declarative approach for making Ajax requests. You can use this tag instead of manually coding the JavaScript for Ajax request calls. This tag serves two roles, depending on the placement. You can nest it within any HTML component or custom component. If you nest it with a single component, it will associate an Ajax action with that component.

The <f:ajax> tag has four important attributes:

  • render – ID or a space-delimited list of component identifiers that will be updated as a result of the Ajax call
  • execute – ID or a space-delimited list of component identifiers that should be executed on the server
  • event – The type of event the Ajax action will apply to (refers to a JavaScript event without the on prefix)
  • onevent – The JavaScript function to handle the event

Consider the following code from the login page of the online quiz application. The code validates the input of the email field by sending an Ajax call for every keystroke. The validation is done by a managed bean method that acts as a value change listener.

<h:inputText label=”eMail ID”   id=”emailId” value=”#{userBean.email}” size=”20″

required=”true” valueChangeListener=”#{userBean.validateEmail}”>

<f:ajax event=”keyup” render=”emailResult”/>

</h:inputText>

<h:outputText id=” emailResult” value=”#{userBean.emailPrompt}” />

 Inside JSF 2.0s Ajax and HTTP GET Support

Using Ajax to Validate the Input: The online quiz application validates email field input by sending an Ajax call for every keystroke.

Here, <f:ajax> is nested within the emailId inputText component. For every keyup event that is generated, an Ajax call is sent to the server, which invokes the valueChangeListener. By default, the component in which the tag is nested is executed on the server. So, the execute attribute is not specified. Also, for an input component, the default event is valueChange, so the event attribute is also not used. The render attribute indicates that the outputText component emailResult should be updated after the Ajax call.

If you place this tag around a group of components, it will associate an Ajax action with all the components that support the events attribute.

<f:ajax event=”mouseover”>

<h:inputText id=”input1″ …/>

<h:commandLink id=”link1″ …/>

</f:ajax>

In this example, input1 and link1 will exhibit Ajax behavior on a mouseover event.

<f:ajax event=”mouseover”>

<h:inputText id=”input1″ …>

<f:ajax event=”keyup”/>

</h:inputText>

<h:commandLink id=”link1″ …/>

</f:ajax>

In this example, input1 and link1 exhibit Ajax behavior on keyup and mouseover events, respectively.

Using the Ajax tag enhances the markup of the associated component to include a script that triggers the Ajax request. This the page author to issue Ajax requests without having to write any JavaScript code.

These new features enable developers to build truly dynamic web pages simply and easily.

http://www.developer.com

http://www.all1sourcetech.com

Tags: , , , , , ,
Posted in Expert's Opinions, Purely Technical | No Comments »

SuzanneUse JavaMail to Automate Email Distribution

Saturday, March 6th, 2010

Every action can possibly be automated with software, then why not automate the email distribution to end-users/customers. In this case, the JavaMail API, currently in version 1.4.3, can support this development in a protocol-independent manner and remain platform independent as always.

Here’s the JavaMail code for sending the email:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;

class EmailClient
{
    final String emailInfo = "EmailInfo.properties";
    Properties properties = new Properties();

    public static void main(String args[])
    {
        EmailClient emailClient = new EmailClient ();
        emailClient.sendEmail();
    }

    private void sendEmail()
    {
       try{
            //This is required to load all the properties
           FileInputStream fileInputStream = new FileInputStream(emailInfo);
           properties.load(fileInputStream);
           fileInputStream.close();
        }catch(IOException ioe)
       {
            //throw IOException of your choice.
            //can end here
       }
        System.out.println("Email properties read successfully.");

       String smtpAddress = properties.getProperty("smtpAddress");
       String fromAddress = properties.getProperty("fromAddress");
       String toAddress = properties.getProperty("toAddress");
       String emailSubject = properties.getProperty("emailSubject");
       String emailBody = properties.getProperty("emailBody");

       Properties props = new Properties();
        props.put("mail.smtp.host", smtpAddress);
        props.put("mail.from", fromAddress);
       Session session = Session.getInstance(props, null);

       try
       {
           MimeMessage mimeMessage = new MimeMessage(session);
           mimeMessage.setRecipients(Message.RecipientType.TO,toAddress);
           mimeMessage.setSentDate(new Date());
           mimeMessage.setSubject(emailSubject);
           mimeMessage.setText(emailBody);
           System.out.println("Sending e-mail...");
           Transport.send(mimeMessage);
           System.out.println("e-mail sent.");
       }
        catch(MessagingException me)
       {
           System.out.println("e-mail send failed.");
           me.getMessage();
       }
    }
}

The code is fairly simple to understand:

  • The properties have been loaded for the email to be sent from a properties file. This could come from any other source, such as hardcoded values, a database, a user interface, etc.
  • The processed information is updated to the MimeMessage object, which is the actual email object. (The MIME, or Multipurpose Internet Mail Extensions, is an Internet standard that specifies how messages must be formatted for interoperability.)
  • MimeMessage takes a session argument, which can either be created or refer to the default session.
  • The session—important in any context and used here for the email—is established using the properties mail.smtp.host and mail.from.
  • Other details such as the date, subject, and the body of the email, which will be used when the email is sent, are being set out.
  • Finally, the email is dispatched using the send() method of the Transport class.
  • The entire email information is made available in a properties file. Here are the contents of the properties file for this application:

smtpAddress=smtp.server.address
fromAddress=myself@me.com
toAddress=someone@you.com
emailSubject=First email
emailBody=My first email

It’s stated previously that the source of the required information can vary, so we can modify the entries at will without recompiling the code to experiment. By the way, holding configurable information in properties files is a standard programming practice.

It seems to be simple right, and now let’s add more advanced features to the application. Don’t you think, you need attachments with email? The following code creates that-

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
import java.io.*;

class SendAdvancedEmail
{
    final String emailInfo = "EmailInfo.properties";
    Properties properties = new Properties();

    public static void main(String args[])
    {
        SendAdvancedEmail sendAdvancedEmail = new SendAdvancedEmail ();
        sendAdvancedEmail.sendEmail();
    }

    private void sendEmail()
    {
       try{
            //This is required to load all the properties
           FileInputStream fileInputStream = new FileInputStream(emailInfo);
           properties.load(fileInputStream);
           fileInputStream.close();
        }catch(IOException ioe)
       {
            //throw IOException of your choice.
            //can end here
       }
        System.out.println("Email properties read successfully.");

       String smtpAddress = properties.getProperty("smtpAddress");
       String fromAddress = properties.getProperty("fromAddress");
       String toAddress = properties.getProperty("toAddress");
       String emailSubject = properties.getProperty("emailSubject");
       String emailBody = properties.getProperty("emailBody");

       Properties props = new Properties();
        props.put("mail.smtp.host", smtpAddress);
        props.put("mail.from", fromAddress);
       Session session = Session.getInstance(props, null);

       try
       {
           MimeMessage mimeMessage = new MimeMessage(session);
           mimeMessage.setRecipients(Message.RecipientType.TO,toAddress);
           mimeMessage.setSentDate(new Date());
           mimeMessage.setSubject(emailSubject);
            //The following is required to add attachments
           MimeMultipart multipart = new MimeMultipart();
           //Creating the text part of the email message
           BodyPart bodyPart = new MimeBodyPart();
            //The type is set to "text/plain"
           bodyPart.setText(emailBody);
           //Creating the attachment part of the email message
           BodyPart attachment = new MimeBodyPart();
           DataSource source = new FileDataSource(emailInfo);
           attachment.setDataHandler(new DataHandler(source));
           attachment.setFileName(emailInfo);
           //attachment.setContent(properties, "text/html");
            //Now combining the email message and the attachment
           multipart.addBodyPart(bodyPart);
           multipart.addBodyPart(attachment);
           //Setting the message with the multipart just created
           mimeMessage.setContent(multipart);

           System.out.println("Sending e-mail...");
           Transport.send(mimeMessage);
           System.out.println("e-mail sent.");
       }
        catch(MessagingException me)
       {
           System.out.println("e-mail send failed."+me);
           me.getMessage();
       }
    }
}

The important difference between this code listing and the one for sending email in the previous section is the process of building the message body, which is now capable of adding a file as an attachment. The Multipart class is actually split into two sections, the message part and the attachment. The properties are actually the same as for the previous code listing.

You could use Multipart instead of MimeMultipart, but be aware that Multipart is an abstract class and hence requires you to create an instance of MimeMultipart. It’s a similar case with MimeMessage. You can use Message, which also is an abstract class. Understanding all the classes used here will help you familiarize yourself with the mail package.

The article has provided enough information for you to experiment with sending and receiving emails. But you need to know-

  • The details in the properties file must be accurate to achieve the desired results.
  • Ensure that you have mail.jar and activation.jar in your classpath.

http://www.all1martpro.com
http://www.all1sourcetech.com

Tags: , , , , , , ,
Posted in Editorial, Purely Technical | No Comments »

NaggieMySQL Profiler Plugin for WordPress

Saturday, March 6th, 2010

WordPress is so flexible that it has not only made it a major hit but also made non-developers to customize it with ease. Most of the Wordpress functions are optimized for acceptable performance, incorrect usage can cause undesirable speed loss.

Code Profiling

A (code) profiler is a performance analysis tool that measures only the frequency and duration of function calls, but there are other specific types of profilers in addition to more comprehensive profilers, capable of gathering extensive performance data.

You may not notice any performance issues unless you use code profiling to assist you. For general PHP profiling, programmers often use xdebug with all sort of PHP applications including wordpress. But, if you’re a wordpress theme developer, usually all you need is a MySQL profiler.

WP MySQL Profiler

This simple plugin will assist both theme and plugin developers in MySQL Profiling. Once installed, MySQL statistics will be available at page footer.

Installation

  • Download WP MySQL Profiler and extract the archive.
  • Rename your wp-db.php file in wp-includes directory to wp-db-backup.php.
  • Upload wp-db.php included in the archive to your wp-includes directory.
  • Upload wpSqlProfiler.php to wp-content/plugins/ directory.
  • Edit your wp-config.php. Find define (‘WPLANG’, ”); and add below:               define(’SAVEQUERIES’, true);
  • Enable “WP MySQL Profiler” plugin from the admin CP.

Usage

You will see MySQL query details at page footer, when you will log in as an admin. Keep an eye on both total queries and time. Each time you add code to your templates, use the profiling information to check if an optimized function or code snippet has been used.

If you notice high total queries or time, examine the queries and check the backtrace (below) to find where the query originated from. And then remove or replace the unoptimized function/code.

The Backtrace

screenshot 031 MySQL Profiler Plugin for WordPress

In the profiler, third column will give you the most important information. It started at themes/default/single.php on line 7 with the function get_header() which called function wp_head(), kubrick_header_display() and finally get_option() in the file functions.php on line 83.

Note that there’s a link “Show Full Trace”. For simplicity, the profiler doesn’t show all the function calls by default. Instead, it tries to determine function calls from plugins and themes. Since you are going to use it when coding plugins and themes, it makes sense to assume that you’re concerned with function calls originating therein.

Final Steps

And if you want to use the same wordpress copy on a live site, make sure to:

  • delete the wp-db.php and rename wp-db-backup.php to wp-db.php. (optional)
  • remove define(‘SAVEQUERIES’, true); from wp-config.php.

Similarly, disable the WP MySQL Profiler plugin.

http://get-a-designer.com

http://www.all1sourcetech.com

Tags: , , , ,
Posted in New Product Release, Purely Technical | No Comments »

NaggieHow to Integrate Google Buzz to your WordPress Theme

Saturday, March 6th, 2010

Google Buzz is a new social media service introduced by Google to share real-time updates. It is integrated directly with your gmail account. It can be integrated just like Twitter in your blog to let your readers share your blogs posts with their followers.

To generate a “Share to Google Buzz” link, you just need to add the following code in between your WordPress Posts Loop.

<a href=’http://www.google.com/reader/link?url=<?php the_permalink(); ?>&title=<?php the_title(); ?>&snippet=<?php the_title(); ?>&srcURL=<?php bloginfo(’wpurl’); ?>&srcTitle=<?php bloginfo(’name’); ?>’>Share to Google Buzz</a>

The link contains 4 parameters:

url: link to blog post
title: blog post title
srcURL: source url like your blog url
srcTitle: your blog name or title

It’s a simplest and plugin free way to add Google Buzz to your blog posts. If you want, you can add a Google Buzz icon instead of text link in the above code.

Tags: , , , , , , ,
Posted in New Product Release, Purely Technical | No Comments »

NaggieHow to build a PHP Link Scraper with cURL?

Thursday, March 4th, 2010

Let’s build a robot, which scrapes links from web pages and dumps them in a database, and then it read those links from the database and follows them, scraping up the links on those pages, and so on ad infinitum.

To begin, let’s have a look at the groundwork.

The cURL Component-

cURL (or “client for URLS”) is a command-line tool for getting or sending files using URL syntax. It was first used in 2007 by Daniel Stenberg as a way to transfer files via protocols such as HTTP, FTP, Gopher, and many others, via a command-line interface. Since then, many more contributors has participated in further developing cURL, and the tool is used widely today.

Using cURL with PHP-

PHP is one of the languages that provide full support for cURL. (Find a listing of all the PHP functions you can use for cURL.) Luckily, PHP also enables you to use cURL without invoking the command line, making it much easier to use cURL while the server is executing. The example below demonstrates how to retrieve a page called example.com using cURL and PHP.

<?php
$ch = curl_init(”http://www.example.com/”);
$fp = fopen(”example_homepage.txt”, “w”);
curl_setopt($ch, cURLOPT_FILE, $fp);
curl_setopt($ch, cURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

<?php


$ch = curl_init(”http://www.example.com/”);
$fp = fopen(”example_homepage.txt”, “w”);


curl_setopt($ch, cURLOPT_FILE, $fp);
curl_setopt($ch, cURLOPT_HEADER, 0);


curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

The Link Scraper-

For the link scraper, you will use cURL to get the content of the page you are looking for, and then you will use some DOM to grab the links and insert them into your database. You can build the database from the information below; it is really simple stuff.

$query = mysql_query(”select URL from links where visited != 1);
if($query)
{

 	while($query = mysql_fetch_array($result))
 	{

$target_url = $query['url'];
$userAgent = ‘ScraperBot’;

Next, grab the URL from the database table inside a simple while loop.

$ch = curl_init();
curl_setopt($ch, cURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, cURLOPT_URL,$target_url);

After instantiating cURL, you use curl_setopt() to set the USER AGENT in the HTTP_REQUEST, and then tell cURL which page you are hoping to retrieve.

curl_setopt($qw, cURLOPT_FAILONERROR, true);
curl_setopt($qw, cURLOPT_FOLLOWLOCATION, true);
curl_setopt($qw, cURLOPT_AUTOREFERER, true);
curl_setopt($qw, cURLOPT_RETURNTRANSFER,true);
curl_setopt($qw, cURLOPT_TIMEOUT, 20);

You’ve set a few more HEADERS with curl_setopt(). This time, you made sure that when an error occurs the script will return a failed result, and you set the timeout of each page followed to 20 seconds. Usually, a standard server will time-out at 30 seconds, but if you run this from your localhost you should be able to set up a no-timeout server.

$html= curl_exec($qw);
if (!$html)
{

 	echo "ERROR NUMBER: ".curl_errno($ch);
 	echo "ERROR: ".curl_error($ch);
 	exit;

}

Grab the actual page by sending the HEADERS along while executing the cURL request using curl_exec(). If an error occurs, it will be reported to PHP by the number and description inside curl_errno() and curl_error, respectively. Obviously, if such an error exists, you exit the script.

$dom = new DOMDocument();
@$dom->loadHTML($html);

Next, you create a document model of your HTML (that you grabbed from the remote server) and set it up as a DOM object.

$xpath = new DOMXPath($dom);
$href = $xpath->evaluate(”/html/body//a”);

Use XPATH to grab all the links on the page.

for ($i = 0; $i < $href->length; $i++) {

 	$data = $href->item($i);
        $url = $data->getAttribute('href');
 	$query = "INSERT INTO links (url, gathered_from) VALUES ('$url', '$gathered_from')";
 	mysql_query($query) or die('Error, insert query failed');
        echo "Successful Link Harvest: ".$url;
 	}

}

Dump all the links into the database, as well as the URL they are gathered from, just so you never go back there again. A more intelligent system might have a separate table for URLs already visited, as well as a normalized relationship between the two.

Going a step further than just grabbing the links enables you to harvest images or entire HTML documents as well. This is kind of where you start when building a search engine. Creating your own search engine may seem naively ambitious, and this little bit of code may inspire you a bit.

Source:- http://www.developer.com

http://www.all1social.com

http://www.all1martpro.com

Tags: , , , , ,
Posted in Editorial, Expert's Opinions, Purely Technical | No Comments »