Popular Posts

Saturday, 21 December 2013

Using Google Co-op's Custom Search Engine

Using Google Co-op's Custom Search Engine



Using google free api you can add a search Engine for your own website ,just need to have a gmail id and follow these steps:

Creating Your Search Engine

The very first step you must take is to visit http://www.google.com/coop/cse.
 (Note that you must have a Google Account. If you don’t have one, Create one. follow the instructions to create your custom search engine.

Where to Host the Custom Search Engine

You have two options on how you can display your search engine to users: Google can host it for you, or you can host the search box and results on your site. For this article, I opted for the latter.
To configure this option:
  1. Return to the Google Co-op Custom Search Engine site’s home page (http://www.google.com/coop/cse).
  2. Click on the My Search Engines link.
  3. When the list of your custom search engines shows up, click on the link that says “Control Panel”.
  4. Next, click on the link that says “Code”.
  5. Select the radio button next to the option that says “Host a search box and search results on your own site…”.
  6. Also, specify the URL of the page on your site where you want the search results to appear.
  7. Finally, after you select the location where you want to display the AdSense ads in your search results, click the Save Changes button.


AFTER REGISTERING THE WEBSITE YOU GET THE CODE JUST PASTE THE CODE IN DIV TAG ON YOUR PAGE WHERE YOU WANT YOUR SEARCH.FOLLOW THE SCREENSHOTS:


1.REGISTER YOUR SITE




2. CREATE YOUR CUSTOM LOOK AND FEEL




3.EXTRACT THE CODE AND PASTE ON YOUR ASPX PAGE



4.DEMO TEST RESULT FOR SEARCH ON YOUR REGISTERED SITE



----------------------------------------------------------------------------------------------------------------------

TO CREATE COUNTDOWN TIMER USING AJAX IN ASP.NET

TO CREATE COUNTDOWN TIMER USING AJAX IN ASP.NET


Friends today we will see how to create a countdown timer with the help of ajax.
 

THE DESIGN PAGE:


You need to frst Register the AJAXCONTROLTOOLKIT in your ASPX page .
then follow the simple code:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="testpage.aspx.cs" Inherits="testpage" MasterPageFile="~/MasterPages/MasterPage.master"%>

 <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

   
    <style type="text/css">
        .circle
        {
         text-align:center;
        float:left;
        width:60px;
        height:60px;
        background-color:#ffffff;
        border: 1px solid #000000;
        padding:20px 20px 20px 20px;
        -moz-border-radius: 50px;
        -webkit-border-radius: 50px;
        border-radius: 50px;
     
         font-family:Cambria;
         font-size:35px;
        }
        .styletable
        {
          font-family:Cambria;
            font-size:15px;
         font-weight:bold;
        }
     </style>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server">

  
    <div id="countdowntimerform" runat="server"><br />
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
         <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
        </asp:Timer>
        <br />
        <br />
        <table width="260">
        <tr>
         <td><div class="circle"><asp:Label ID="Label1" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label2" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label3" runat="server"></asp:Label></div></td>
         <td><div class="circle"><asp:Label ID="Label4" runat="server"></asp:Label></div></td>
        </tr>
        <tr align="center"><td><b>DAYS</b></td><td><b>HOURS</b></td><td><b>MIN</b></td><td><b>SEC</b></td></tr></table
        </ContentTemplate>
        </asp:UpdatePanel>
         </div>
   </asp:Content>


THE CODE BEHIND:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data;

public partial class testpage : System.Web.UI.Page
{
    static DateTime setdt;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        { 
            
        
            DateTime time = DateTime.Now;              // Use current time
            string format = "d mm yyyy HH:mm:ss ";    // Use this format
            Console.WriteLine(time.ToString(format));  // Write to console


          DateTime  date1 = (time.AddMinutes(3));  
//HERE I HAVE ADDED THE TIMER TO 3 MINUTES FROM THE CURRENT TIME.SO THE //COUNTDOWN WILLSTARTS WITH 3 MINUTES REMAINING.
  
        Session["addedtime"] = date1;
          Timer1.Enabled = true;
        }
    }


    protected void Timer1_Tick(object sender, EventArgs e)
    {
        DateTime dt = DateTime.Now;
        TimeSpan differ;
        
      //   System.DateTime date1 = new System.DateTime();
        DateTime date1 = (DateTime)Session["addedtime"];
        differ = date1.Subtract(dt);
        double t = differ.TotalSeconds;

        if (t > 0)
        {
            double yr, mnth, dy, h, m, s;
            dy = differ.Days;
            h = differ.Hours;
            m = differ.Minutes;
            s = differ.Seconds;
            Label1.Text = dy.ToString();// +" Days " + h + " Hours " + m + " Minutes " + s + " Seconds left for celebration";
            Label2.Text = h.ToString();
            Label3.Text = m.ToString();
            Label4.Text = s.ToString();
        }
        else
        {
            Timer1.Enabled = false;
//and perform your other logic here
        }
    }
   
}

 

SENDING SMS THROUGH ASP.NET PROGRAMM

SENDING SMS OTP(ONE TIME  PASSWORD) TO USER MOBILE NO.


Hello friends this post explains the way where you can send the sms to any user mobile ,where i am sending or applying the concept on OTP to be send to registered user for his authentication.

In general, there are two ways to send SMS messages from a computer / PC to a mobile phone:
  1. Connect a mobile phone or GSM/GPRS modem to a computer / PC. Then use the computer / PC and AT commands to instruct the mobile phone or GSM/GPRS modem to send SMS messages.
  2. Connect the computer / PC to the SMS center (SMSC) or SMS gateway of a wireless carrier or SMS service provider. Then send SMS messages using a protocol / interface supported by the SMSC or SMS gateway.
HERE WE WILL DISCUSS THE SECOND WAY.TO REFER THE FIRST WAY I FOUND AN ARTICLE  ON CODE PROJECT:

THE DESIGN PAGE:

The design page will consists of user register form where he fills up the data and wait to recieve the sms code and need to enter the OTP and validation will be done.


THE CODE BEHIND:
TO SEND SMS:


this is the simple function created to send the OTP  to user mobile no:

   protected Int32 sendonetimepass(string username, string mobileno, string emailid)
    {
        try
        {
         

            Random _r = new Random();  //random number function to generate OTP

            int n = _r.Next(10000);


            System.IO.Stream Str = null;
            System.IO.StreamReader srRead = null;  //object of streamReader
            string PageContent = null;
            string strTmpContact = string.Empty;
            string message = "Dear User " + username + " ,Your One Time Password(OTP) is " + n + " ,please enter to confirm your identity/authenticity";
            if (n > 0)
            {
                string url = ("http://www.URPROVIDER.in/SendTestSMS/SendTESTMsg.php?uname=URREGISTERDNAME&pass=URPASSWORD&send=URREGISTRATIONNO&dest=91" + mobileno + "&msg=TITLE_OF_MESSAGE ") + message + "";


// the string Url consistis of  the the url string provided to u by the SERVICE PROVIDER TO SEND SMS.
// You can send SMS using ASP.net web application. First you hunt for good SMS provider API.    //API should be capable of sending long messages more than 160 characters.    //It works with http Get Method. Below is the code snippet to deal with an API.                


 System.Net.WebRequest req = System.Net.WebRequest.Create(url);
                System.Net.WebResponse resp = req.GetResponse();
                Str = resp.GetResponseStream();
                srRead = new System.IO.StreamReader(Str);
                // read all the text
                PageContent = srRead.ReadToEnd();

            }
            if ((srRead != null) & (Str != null))
            {
                srRead.Close();
                Str.Close();
            }
            return n;
        }

        catch (Exception ex)
        {
            return 0;

        }

    }



TO VALIDATE THE SMS ENTERED BY USER:

Once the sms is send successfully then you can save the sms of the user with his name and others details in the DB and can check when he enters.LIKE:



string query = "insert into userotpdetails values('" + txtUserName.Text + "','" + txtUserID.Text + "','" + txtPassword.Text + "','" + txtMobile.Text + "','" + txtEmailID.Text + "'," + otp + ",'" + currentdatetime + "')";
                DBAccess obj1 = new DBAccess();
                string result = obj1.OracleExecute(query);
                if (result == "Success")
                {
SYSTEM.OUT.PRINTLN("DETAILS SUBMMITED SUCCESFULLY");
               }

----------------------------------------------------------------------------------------------------------

Sunday, 29 September 2013

How do database indexes work/How to Create database index

How do database indexes work/How to Create database index


Let’s start out our tutorial and explanation of why you would need a database index by going through a very simple example
SUPPOSE we have a database table named EMP as:
desc emp
Name     Null     Type        
-------- -------- ------------
EMPNO    NOT NULL NUMBER(4)   
ENAME             VARCHAR2(10)
JOB               VARCHAR2(9) 
MGR               NUMBER(4)   
HIREDATE          DATE        
SAL               NUMBER(7,2) 
COMM              NUMBER(7,2) 
DEPTNO            NUMBER(2) 


And we query as:

SELECT * FROM emp WHERE ename = 'KING'
OUTPUT:
EMPNO                  ENAME      JOB       MGR                    HIREDATE                  SAL                    COMM                   DEPTNO                
---------------------- ---------- --------- ---------------------- ------------------------- ---------------------- ---------------------- ----------------------
7839                   KING       PRESIDENT                        17-11-81                  5000                                          10                    


What would happen without an index on the table?

Once we run that query, what exactly goes on behind the scenes to find employees who are named KING? Well, the database software would literally have to look at every single row in the Employee table to see if the Enamefor that row is ‘KING’. And, because we want every row with the name ‘KING’ inside it, we can not just stop looking once we find just one row with the name ‘KING’, because there could be other rows with the name KING. So, every row up until the last row must be searched – which means thousands of rows in this scenario will have to be examined by the database to find the rows with the name ‘KING’. This is what is called a FULL TABLE SCAN....

 

How a database index can help performance..


The whole point of having an index is to speed up search queries by essentially cutting down the number of records/rows in a table that need to be examined.

What is an index?

So, what is an index? Well, an index is a data structure (most commonly a B- tree) that stores the values for a specific column in a table. An index is created on a column of a table. So, the key points to remember are that an index consists of column values from one table, and that those values are stored in a data structure. The index is a data structure – remember that.

How does a hash table index work?

Hash tables are another data structure that you may see being used as indexes – these indexes are commonly referred to as hash indexes. The reason hash indexes are used is because hash tables are extremely efficient when it comes to just looking up values. So, queries that compare for equality to a string can retrieve values very fast if they use a hash index. For instance, the query we discussed earlier (SELECT * FROM Employee WHERE Ename= ‘KING’) could benefit from a hash index created on the Ename column. The way a hash index would work is that the column value will be the key into the hash table and the actual value mapped to that key would just be a pointer to the row data in the table. Since a hash table is basically an associative array, a typical entry would look something like “KING => 0×28939″, where 0×28939 is a reference to the table row where KING is stored in memory. Looking up a value like “KING” in a hash table index and getting back a reference to the row in memory is obviously a lot faster than scanning the table to find all the rows with a value of “KING” in the Ename column.

The disadvantages of a hash index

Hash tables are not sorted data structures, and there are many types of queries which hash indexes can not even help with. For instance, suppose you want to find out all of the employees who are less than 40 years old. How could you do that with a hash table index? Well, it’s not possible because a hash table is only good for looking up key value pairs – which means queries that check for equality (like “WHERE name = ‘KING’”). What is implied in the key value mapping in a hash table is the concept that the keys of a hash table are not sorted or stored in any particular order.

What are some other types of indexes?

Indexes that use a R- tree data structure are commonly used to help with spatial problems. For instance, a query like “Find all of the Starbucks within 2 kilometers of me” would be the type of query that could show enhanced performance if the database table uses a R- tree index.


What exactly is inside a database index?

So, now you know that a database index is created on a column in a table, and that the index stores the values in that specific column. But, it is important to understand that a database index does not store the values in the other columns of the same table. For example, if we create an index on the Ename column, this means that the Job and emp_no or dept_no column values are not also stored in the index. If we did just store all the other columns in the index, then it would be just like creating another copy of the entire table – which would take up way too much space and would be very inefficient.

How does a database know when to use an index?

When a query like “SELECT * FROM Employee WHERE Ename= ‘KING’ ” is run, the database will check to see if there is an index on the column(s) being queried. Assuming the Ename column does have an index created on it, the database will have to decide whether it actually makes sense to use the index to find the values being searched – because there are some scenarios where it is actually less efficient to use the database index, and more efficient just to scan the entire table.

Can you force the database to use an index on a query?

Generally, you will not tell the database when to actually use an index – that decision will be made by the database itself. Although it is worth noting that in most databases (like Oracle and MySQL), you can actually specify that you want the index to be used.


How to create an index in SQL:

Here’s what the actual SQL would look like to create an index on the Employee_Name column from our example earlier:
CREATE INDEX name_index
ON Emp (Ename)

How to create a multi-column index in SQL:

We could also create an index on two of the columns in the Employee table , as shown in this SQL:
CREATE INDEX name_index
ON Employee (ENAME, HIREDATE)


What is the cost of having a database index?

So, what are some of the disadvantages of having a database index? Well, for one thing it takes up space – and the larger your table, the larger your index. Another performance hit with indexes is the fact that whenever you add, delete, or update rows in the corresponding table, the same operations will have to be done to your index. Remember that an index needs to contain the same up to the minute data as whatever is in the table column(s) that the index covers.
As a general rule, an index should only be created on a table if the data in the indexed column will be queried frequently.


HOW TO CHECK COST OF YOUR SQL QUERY ON CPU and PROCESSING TIME

HOW TO CHECK COST OF YOUR SQL QUERY ON CPU and PROCESSING TIME

IF YOUR QUERY IS TAKING TOO MUCH TIME FOR OUTPUTING THE RESULT THEN SOMETHING IS WRONG...EITHER THE QUERY IS NOT OPTIMIZED OR SAY THE INDEX ARE NOT SET ON THE CROSSPONDING TABLES COLUMNS...ETC..
THUS YOU NEED TO FIGURE IT OUT ??????????????????????????
Its quite simple in oracle ..THE EXPLAIN Command help us to fid the cost of processing the query.
this need to be Done on cmd .lets see how?

1. first you need to log on to the database you are using using the credentials,then enter the following command followeded by your query-

SQL>  Explain plan for select a.rain-b.rain as "02:30:00+05:30"  from  rainfall_2010 a,rainfall_2010 b  where  a.raingauge=452 and b.raingauge=452 and a.raindate=to_date('03-07-2010','dd-MM-yyyy' ) and b.rainda
te=to_date('03-07-2010','dd-MM-yyyy' )  and a.raintime= ('02:30:00+05:30') and b.raintime=('01:30:00+05:30');

Explained.

SQL> set long 999999999
SQL> set lines 3000
SQL> @?/rdbms/admin/utlxpls.sql

PLAN_TABLE_OUTPUT
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------

---------------------------------------------------------------------------
| Id  | Operation            | Name          | Rows  | Bytes | Cost (%CPU)|
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT     |               |     1 |    60 | 29289   (2)|
|   1 |  MERGE JOIN CARTESIAN|               |     1 |    60 | 29289   (2)|
|   2 |   INDEX SKIP SCAN    | INDX_RAINFALL |     1 |    30 |   361   (0)|

|   3 |   BUFFER SORT        |               |     1 |    30 | 28928   (2)|
|   4 |    TABLE ACCESS FULL | RAINFALL_2010 |     1 |    30 | 28928   (2)|

---------------------------------------------------------------------------



PLAN_TABLE_OUTPUT

Thus here you can see that we get all the operation that are being performed when the query executes .
here we can simply figure it out that TABLE ACCESS FULL | RAINFALL_2010 is done hence the cost is high .
this is due to non availblity of index on the table.

after correcting the necessary things when we again executed the plan then we got much better cost.

-----------------------------------------------------------------------
| Id  | Operation        | Name          | Rows  | Bytes | Cost (%CPU)|
-----------------------------------------------------------------------
|   0 | SELECT STATEMENT |               |     1 |    60 |   722   (1)|
|   1 |  HASH JOIN       |               |     1 |    60 |   722   (1)|
|   2 |   INDEX SKIP SCAN| INDX_RAINFALL |     1 |    30 |   361   (0)|

|   3 |   INDEX SKIP SCAN| INDX_RAINFALL |     1 |    30 |   361   (0)|-----------------------------------------------------------------------


THus it help you to analyze your query and take necessary action.

To see WHAT IS INDEX ,WHY TO PUT INDEX,HOW TO PUT INDEX VISIT THE ARTICLE:


HOW TO CONVERT WEBPAGE INTO PDF FILE

HOW TO CONVERT WEBPAGE INTO PDF FILE

Here I will explain how to export webpage with images to PDF in asp.net using iTextSharp in c#, vb.net.

In asp.net we don’t have a direct feature to export gridview data to PDF for that reason here I am using third party library ITextSharp reference. First download dll from this site http://sourceforge.net/projects/itextsharp/[^]
OR
after that create one new website in visual studio and add ITextsharp dll reference to newly created website after that write the following code in aspx page like this


THE CODE DESIGN :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebpageToPdf.aspx.cs" Inherits="WebpageToPdf" EnableEventValidation="false"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form id="form1" runat="server">

<div><b>Export Webpage with images to pdf using itextsharp dll</b></div><br />
<div>
THIS IS THE TEST IMAGE ADDED FROM INTERNET:
 
  <div><img src="http://i328.photobucket.com/albums/l336/glamgalz/funzug/imgs/inspirational/cool_thoughts_persons_08.jpg" /></div>
 
  THIS IS THE TEST IMAGE ADDED FROM WEBAPPLICATION/PC FOLDER:
   <div>       <img src="images/thumbs/13.jpg" /></div>


</div>

<div>
SOME CONTENT IN WEB PAGE:
<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
<asp:Button ID="btnPDF" runat="server" Text="Export to PDF" OnClick="btnPDF_Click"/>
</form>
</body>
</html>YOU HAVE NOTICE THAT I HAVE KEPT EnableEventValidation="false" in bold due to following reason:
ERROR :
RegisterForEventValidation can only be called during Render();

This error occurs whenever we are trying to render control to response. To solve this problem I have added EnableEventValidation="false" to @Page directive of aspx page that should be just like this 

By Setting EnableEventValidation="false" property to @Page directive of aspx page the problem has solved automatically.




THE CODE BEHIND:



using System;
using System.Web;
using System.Web.UI;
using System.Data;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

public partial class WebpageToPdf : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridview();
        }
    }
    protected void BindGridview()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("UserName", typeof(string));
        dt.Columns.Add("Education", typeof(string));
        dt.Columns.Add("Location", typeof(string));
        DataRow dtrow = dt.NewRow();    // Create New Row
        dtrow["UserId"] = 1;            //Bind Data to Columns
        dtrow["UserName"] = "PIYUSHRANA";
        dtrow["Education"] = "B.Tech";
        dtrow["Location"] = "NOIDA";
        dt.Rows.Add(dtrow);
        dtrow = dt.NewRow();               // Create New Row
        dtrow["UserId"] = 2;               //Bind Data to Columns
        dtrow["UserName"] = "PRAVEEN";
        dtrow["Education"] = "MBA";
        dtrow["Location"] = "MUMBAI";
        dt.Rows.Add(dtrow);
        dtrow = dt.NewRow();              // Create New Row
        dtrow["UserId"] = 3;              //Bind Data to Columns
        dtrow["UserName"] = "GANESH";
        dtrow["Education"] = "B.Tech";
        dtrow["Location"] = "MUMBAI";
        dt.Rows.Add(dtrow);

        dtrow = dt.NewRow();              // Create New Row
        dtrow["UserId"] = 3;              //Bind Data to Columns
        dtrow["UserName"] = "MAHESH";
        dtrow["Education"] = "B.Tech";
        dtrow["Location"] = "CHENNAI";
        dt.Rows.Add(dtrow);
        dtrow = dt.NewRow();              // Create New Row
        dtrow["UserId"] = 3;              //Bind Data to Columns
        dtrow["UserName"] = "SANDEEP";
        dtrow["Education"] = "B.Tech";
        dtrow["Location"] = "MUMBAI";
        dt.Rows.Add(dtrow);

        gvDetails.DataSource = dt;
        gvDetails.DataBind();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
    protected void btnPDF_Click(object sender, EventArgs e)
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        //if you want to add/insert images from your folder then add the below two lines
        string imageFilePath = Server.MapPath(".") + "/images/thumbs/13.jpg";
        iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(imageFilePath);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        this.Page.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0.0f);
      
       png.ScaleToFit(110, 110);
        png.Alignment = iTextSharp.text.Image.UNDERLYING;
          png.SetAbsolutePosition(480, 800);

        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        pdfDoc.Add(png);
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
}