Wednesday, 23 January 2013

Make Your Own Search Engine....!

 Click Here

1.Select " Make Your Search Engine URL "

2.Select Style

3.Enter Your Name

4.Create

Custom DateTime Formatting

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed),t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
[C#]
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator andDateTimeForma­tInfo.TimeSepa­rator.
[C#]
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:
[C#]
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
SpecifierDateTimeFormatInfo propertyPattern value (for en-US culture)
tShortTimePatternh:mm tt
dShortDatePatternM/d/yyyy
TLongTimePatternh:mm:ss tt
DLongDatePatterndddd, MMMM dd, yyyy
f(combination of D and t)dddd, MMMM dd, yyyy h:mm tt
FFullDateTimePatterndddd, MMMM dd, yyyy h:mm:ss tt
g(combination of d and t)M/d/yyyy h:mm tt
G(combination of d and T)M/d/yyyy h:mm:ss tt
m, MMonthDayPatternMMMM dd
y, YYearMonthPatternMMMM, yyyy
r, RRFC1123Patternddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
sSortableDateTi­mePatternyyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
uUniversalSorta­bleDateTimePat­ternyyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
  (*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting output.
[C#]
String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime

Watermark in textbox using JavaScript


In the web application development, developers always try to make UI more user-friendly and interactively. Showing watermark on textbox is one of the tools to increase user-interactivity of website. Most of the sites use the watermark mainly for “Search” functionality. In this post I will show you a simple implementation of watermark in textbox using JavaScript.
So, let’s start the watermark implementation in textbox.

1- Aspx Page
<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtWatermarkDemo" runat="server" CssClass="watermark"></asp:TextBox>
    </div>
 </form>

2- CSS styles for watermark and simple textbox
<style type="text/css">
        .watermark
        {
            font-style:italic;
            font-size:12px;
            color:#C0C0C0;
            width:150px;
        }
        .textbox
        {
            font-style:normal;
            font-size:12px;
            color:#000000;
            width:150px;
        }
    </style>

3- JavaScript Code for watermark
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
//function to remove the search keyword when focus is on textbox
        function onFocusWatermark(txtid,strWatermark) {
            var txtval = txtid.value;
            if (txtval == strWatermark) {
                $(txtid).addClass('textbox');
                $(txtid).removeClass('watermark');              
                txtid.value = '';
            }
        }
//function to show the search keyword when leave the textbox empty
        function onBlurWatermark(txtid, strWatermark) {
            var txtval = txtid.value;
            if (txtval == '') {
                $(txtid).removeClass('textbox');
                $(txtid).addClass('watermark');           
                txtid.value = strWatermark;
            }
        }
 </script>

4- Code behind
protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
     string strSearch = "Search";
     txtWatermarkDemo.Text = strSearch;
     txtWatermarkDemo.Attributes.Add("onFocus", "onFocusWatermark(this,'" + strSearch + "')");
     txtWatermarkDemo.Attributes.Add("onBlur", "onBlurWatermark(this,'" + strSearch + "')");
  }
}

Tuesday, 22 January 2013

Mind Game...!

Free JavaScripts provided
by The JavaScript Source

Auto Complete Extender using Ajax

Introduction

Ajax AutoComplete Extender controls is one of the most popular control in Asp.net. Suppose you are at Google home page and you want to see few story books for kids, so you start typing something like "Kids story book", at the same time Google start suggesting the topics(Auto suggestion), this is the functionality where AutoComplete extender comes into picture in Asp.net.


How to Implement Autocomplete Extender
<asp:AutoCompleteExtender  ID="Story_AutoCompleteExtender"  runat="server" DelimiterCharacters="" Enabled="True" ServicePath="Story.asmx" ServiceMethod="GetStoryBooks" MinimumPrefixLength="2"  TargetControlID="txtSearchTextBox"> asp:AutoCompleteExtender>
 
 
 
In above code Story.Asmx is my webservice which pulls the data from any datasource. In our case it is XML file.
ServiceMethod: Is your web method
TargetControlID: is your control where you will type your search string

How to Bind search text box with Autocomplete Extender:  Select text box and click the smart tag, now choose the Autocomplete extender.

WebService Code:

[System.Web.Services.WebMethod]
 
public static string[] GetStoryBooks(String prefixText, int count)
{
  List<String> suggestions = new List<string>();
  DataSet dtSuggestedResult = new DataSet();
  dtSuggestedResult = GetStorySuggestionList(prefixText.Trim());
 
   if (dtSuggestedResult.Tables[0].Rows.Count > 0)
      {
        for ( 
               int i = 0; i; 
dtSuggestedResult.Tables[0].Rows.Count; 
i++
)
         {
            string suggestion = 
dtSuggestedResult.Tables[0].Rows[i]["BooksName"].ToString();
            suggestions.Add(suggestion);
         }
     }
   return suggestions.ToArray();
}

Export GridView To Word/Excel/PDF/CSV in ASP.Net

In this article, I will explain how to export GridView to Word, Excel, PDF and CSV formats.
Exporting to Word, Excel and CSV can be easily achieved using ASP.Net without any third party tools, but for exporting GridView to PDF I am using iTextSharp which is a free library for exporting html to PDF.

To start with I have a GridView in which I am showing Customers records from the NorthWind Database.
The HTML markup of the GridView is as shown below
C#
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

<asp:GridView ID="GridView1" runat="server"
    AutoGenerateColumns = "false" Font-Names = "Arial"
    Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" 
    HeaderStyle-BackColor = "green" AllowPaging ="true"  
    OnPageIndexChanging = "OnPaging" >
   <Columns>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "CustomerID"
    HeaderText = "CustomerID" />
    <asp:BoundField ItemStyle-Width = "150px" DataField = "City"
    HeaderText = "City"/>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "Country"
    HeaderText = "Country"/>
    <asp:BoundField ItemStyle-Width = "150px" DataField = "PostalCode"
    HeaderText = "PostalCode"/>
   </Columns>
</asp:GridView>

In the figure below the GridView is shown with four buttons
1.     Export To Word
2.     Export To Excel
3.     Export To PDF
4.     Export To CSV


GridView with Sample Data


Export to Microsoft Word Format

C#
protected void btnExportWord_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
    "attachment;filename=GridViewExport.doc");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-word ";
    StringWriter sw= new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}
 
The above function renders the GridView contents as Microsoft Word format. You will notice I have disabled paging before exporting, so that all the pages are exported.  
The Output Exported File


GridView data exported to Word Document


Export to Microsoft Excel Format

For exporting the document to Excel if you do it directly as done in case of word the row background color is applied throughout to all the columns in the Excel Sheet hence in order to avoid it. I have done a workaround below.
First I am changing the background color of each row back to white.
Then I am applying the background color to each individual cell rather than the whole row. Thus when you export now you will notice that the formatting is applied only to the GridView cells and not all
Also I am applying textmode style class to all cells and then adding the style CSS class to the GridView before rendering it, this ensures that all the contents of GridView are rendered as text.

protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;

Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);

GridView1.AllowPaging = false;
GridView1.DataBind();

//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");

//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");  

for (int i = 0; i < GridView1.Rows.Count;i++ )
{
    GridViewRow row = GridView1.Rows[i];

    //Change Color back to white
    row.BackColor = System.Drawing.Color.White;

    //Apply text style to each Row
    row.Attributes.Add("class", "textmode");

    //Apply style to Individual Cells of Alternating Row
    if (i % 2 != 0)
    {
        row.Cells[0].Style.Add("background-color", "#C2D69B");
        row.Cells[1].Style.Add("background-color", "#C2D69B");
        row.Cells[2].Style.Add("background-color", "#C2D69B");
        row.Cells[3].Style.Add("background-color", "#C2D69B");  
    }
}
GridView1.RenderControl(hw);

//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

  
Output

GridView data exported to Excel Document


Export to Portable Document Format

For exporting the GridView to PDF I am using the iTextSharp Library. You will need to Add Reference for the iTextSharp Library in your Website.
Then import the following Namespaces

C#
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

By default the iTextSharp Library does not support background color of table cells or table rows
Hence when you render it as PDF your GridView is rendered without any formatting.
Recently I read an article on hamang.net where the author has provided the snippet to modify the iTextSharp so that it exports the HTML with background color.

For this tutorial, I have already modified the iTextSharp Library DLL so that the GridView is rendered with all the background color used. You can refer the code for exporting GridView to PDF below
  
              
C#
protected void btnExportPDF_Click(object sender, EventArgs e)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();
    GridView1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f,10f,10f,0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End(); 
}
 
The Output Exported File
GridView data exported to PDF Document


Export to Text/CSV

Finally comes exporting GridView to CSV or Text File delimited by a separator like comma.
To export the GridView as CSV, I am running a two for loops. While looping through the GridView columns and appending comma after each column and while looping through rows appending new line character. Refer the code below.

C#
protected void btnExportCSV_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
     "attachment;filename=GridViewExport.csv");
    Response.Charset = "";
    Response.ContentType = "application/text";

    GridView1.AllowPaging = false;
    GridView1.DataBind();

    StringBuilder sb = new StringBuilder();
    for (int k = 0; k < GridView1.Columns.Count; k++)
    {
        //add separator
        sb.Append(GridView1.Columns[k].HeaderText + ',');
    }
    //append new line
    sb.Append("\r\n");
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            //add separator
            sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
        }
        //append new line
        sb.Append("\r\n");
    }
    Response.Output.Write(sb.ToString());
    Response.Flush();
    Response.End();
}
      

The Output Exported File


GridView data exported to CSV File