Tuesday, December 14, 2010

How to Show Error From Serverside in Javascript

Protected Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error
        Dim ex As Exception
        ex = Server.GetLastError
        If TypeOf (ex) Is HttpException Then
            If ex.ToString.IndexOf("System.Web.HttpException: Maximum request length exceeded") > -1 Then
                Server.ClearError()
                Dim str As String = "<script type=""text/javascript""></script>"
                Dim sb As StringBuilder = New StringBuilder()
                sb.Append("<script>")
                sb.Append("alert(""Nothing DONE!!!\nUploaded File size should not exceed 4 MB. Please Delete Selected File.\nERROR: " + ex.Message + """);window.history.back();")
                sb.Append("document.getElementById(""attachment"").innerText="""";")
                sb.Append("</scri")
                sb.Append("pt>")
                Dim s As String = sb.ToString
                Page.RegisterStartupScript("test", sb.ToString())
            End If
        End If
    End Sub

Sunday, October 31, 2010

How to show client side message from Server Side Code?

File to be uploaded can't be more than 4 MB.

Protected Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Error
        Dim ex As Exception
        ex = Server.GetLastError
        If TypeOf (ex) Is HttpException Then
            If ex.ToString.IndexOf("System.Web.HttpException: Maximum request length exceeded") > -1 Then
                Server.ClearError()
                Dim str As String = "<script type=""text/javascript""></script>"
                Dim sb As StringBuilder = New StringBuilder()
                sb.Append("<script>")
                sb.Append("alert(""Nothing DONE!!!\nUploaded File size should not exceed 4 MB. Please Delete Selected File.\nERROR: " + ex.Message + """);window.history.back();")
                sb.Append("</scri")
                sb.Append("pt>")
                Dim s As String = sb.ToString
                Page.RegisterStartupScript("test", sb.ToString())
            End If
        End If
    End Sub

Wednesday, October 27, 2010

Thread Safety Example

Thread Safety

It's new in .Net 2.0.
It's used to prevent DeadLock.
Thread Safety is a technique that allows us cross thread operation in a safe manor.
Important properties:
→ CheckForIllegalThreadCalls: It's bydefault True. Gets or Sets a value indicating whether to calls on the wrong thread that access a control's System.Windows.Forms.Control.Handle Property when an application is being debugged.
→ InvokeRequire(T, F): it is a property of Control. Default value is true. It means control is in different domain and calling is being done from different domain.

drag and drop two textbox and a button on the page.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Test_Thread1
{
public partial class Form1 : Form
{
ThreadStart ts1,ts2;
Thread th1,th2;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
ts1 = new ThreadStart(abc);
th1 = new Thread(ts1);
th1.Start();
ts2 = new ThreadStart(xyz);
th2 = new Thread(ts2);
th2.Start();
}
private void abc()
{
for (int i = 0; i < 20; i++)
{
mno(textBox1, "IndiaMART InterMESH LTD.");
}
}

private void xyz()
{
for (int i = 0; i < 20; i++)
{
mno(textBox2, "IndiaMART InterMESH LTD New");
}
}

private delegate void MyDelegate(TextBox t1, string S);
private void mno(TextBox t1, string S)
{
if (t1.InvokeRequired)
{
MyDelegate dd = new MyDelegate(mno);
t1.Invoke(dd, t1, S);
}
else
{
t1.Text += Environment.NewLine + S;
}
}
}
}

Thursday, October 7, 2010

How to trim string in javascript?

<script language="JavaScript" type="text/javascript">
<!--
        String.prototype.trim = function() {
            return this.replace(/^\s*/, "").replace(/\s*$/, "");
        }

        var s = new String(" Hello ");
        // use it like this
        s = s.trim();
        alert("!" + s + "!");

// end hiding contents -->
</script>

Friday, October 1, 2010

how to move the title text of tabs in browser

add following code in head of source
<script language="javascript" type="text/javascript">
   var rev = "fwd";
    function titlebar(val) {
        var msg = 'Welcome Naween';
        var res = " ";
        var speed = 100;
        var pos = val;

        //msg = "   |--- " + msg + " ---|";
        var le = msg.length;
        if (rev == "fwd") {
            if (pos < le) {
                pos = pos + 1;
                document.title = msg.substring(0, pos);
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
            else {
                rev = "bwd";
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
        }
        else {
            if (pos > 0) {
                pos = pos - 1;
                var ale = le - pos;
                document.title = msg.substring(ale, le);
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
            else {
                rev = "fwd";
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
        }
    }

    titlebar(0);
</script>

how to add icon at start of link in status bar of Website

Design a logo of logo with the extension .ico
Design the gif of size 32*32 or 16*16
At following code under the head tag at html page
suppose we have a abc.ico and a xyz.gif
<link rel="shortcut icon" href="../abc.ico" >
    <link rel="icon" type="image/gif" href="..xyz.gif">

Tuesday, September 28, 2010

How To Create Line Chart in Asp.net

add an handler and add following code
==========================

using System;
using System.Web;
using IndiamartLineChart;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

public class hdlLineChart : IHttpHandler   {
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/png";
        string ChartVal = context.Request.QueryString["CV"];
        MemoryStream memStream = new MemoryStream();
        Bitmap b;
        LineChart c = new LineChart(600, 300);
        c.Title = "Progress Line Chart";
        c.Xorigin = 29;
        c.ScaleX = 10; c.Xdivs = 10;
        c.Yorigin = 0; c.ScaleY = 10; c.Ydivs = 10;
        if (ChartVal != string.Empty)
        {           
            int stval = 0, endval=0;
            for (int CmnI = 0; CmnI < ChartVal.Split('x').Length - 1; CmnI++)
            {
                stval =  Convert.ToInt32(ChartVal.Split('x')[CmnI].Split(',')[0]);
                endval =  Convert.ToInt32(ChartVal.Split('x')[CmnI].Split(',')[1]);
                if (c.Xorigin != 29) c.Xorigin = stval;
                c.AddValue(stval,endval);
            }
        }
        b = c.Draw();
        b.Save(memStream, ImageFormat.Png);
        memStream.WriteTo(context.Response.OutputStream);
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
  
}


use this in app_code or create a class libray
=============================
public class LineChart
    {
        public LineChart()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public Bitmap b;

        public string Title = "Progress Line Chart";

        public ArrayList chartValues = new ArrayList();

        public float Xorigin = 0, Yorigin = 0;

        public float ScaleX, ScaleY;

        public float Xdivs = 2, Ydivs = 2;

        private int Width, Height;

        private Graphics g;

        //private Page p;

        public LineChart(int myWidth, int myHeight)
        {

            Width = myWidth; Height = myHeight;

            ScaleX = myWidth; ScaleY = myHeight;

            b = new Bitmap(myWidth, myHeight);

            g = Graphics.FromImage(b);

            //p = myPage;

        }
        struct datapoint
        {

            public float x;

            public float y;

            public bool valid;

        }

        public void AddValue(int x, int y)
        {

            datapoint myPoint;

            myPoint.x = x;

            myPoint.y = y;

            myPoint.valid = true;

            chartValues.Add(myPoint);

        }



        public Bitmap Draw()
        {

            int i;

            float x, y, x0, y0;

            string myLabel;

            Pen blackPen = new Pen(Color.YellowGreen, 1);

            Brush blackBrush = new SolidBrush(Color.YellowGreen);

            Font axesFont = new Font("arial", 10);



            //first establish working area

            //p.Response.ContentType = "image/jpeg";

            g.FillRectangle(new SolidBrush(Color.Transparent), 0, 0, Width, Height);
            //g.DrawRectangle(new Pen(Color.Black), 0, 0, Width, Height);
            int ChartInset = 50;

            int ChartWidth = Width - (2 * ChartInset);

            int ChartHeight = Height - (2 * ChartInset);//2

            g.DrawRectangle(new Pen(Color.Blue, 1), ChartInset, ChartInset, ChartWidth, ChartHeight);



            //must draw all text items before doing the rotate below

            g.DrawString(Title, new Font("arial", 14), blackBrush, Width / 3, 10);

            //draw X axis labels

            for (i = 0; i <= Xdivs; i++)
            {

                x = ChartInset + (i * ChartWidth) / Xdivs;

                y = ChartHeight + ChartInset;

                myLabel = (Xorigin + (ScaleX * i / Xdivs)).ToString();

                g.DrawString(myLabel, axesFont, blackBrush, x - 4, y + 10);

                g.DrawLine(blackPen, x, y + 2, x, y - 2);

            }

            //draw Y axis labels

            for (i = 0; i <= Ydivs; i++)
            {

                x = ChartInset;

                y = ChartHeight + ChartInset - (i * ChartHeight / Ydivs);

                myLabel = (Yorigin + (ScaleY * i / Ydivs)).ToString();

                g.DrawString(myLabel, axesFont, blackBrush, 5, y - 2);//6

                g.DrawLine(blackPen, x + 2, y, x - 2, y);

            }



            //transform drawing coords to lower-left (0,0)

            g.RotateTransform(180);

            g.TranslateTransform(0, -Height);

            g.TranslateTransform(-ChartInset, ChartInset);

            g.ScaleTransform(-1, 1);



            //draw chart data

            datapoint prevPoint = new datapoint();

            prevPoint.valid = false;

            foreach (datapoint myPoint in chartValues)
            {

                if (prevPoint.valid == true)
                {

                    x0 = ChartWidth * (prevPoint.x - Xorigin) / ScaleX;

                    y0 = ChartHeight * (prevPoint.y - Yorigin) / ScaleY;

                    x = ChartWidth * (myPoint.x - Xorigin) / ScaleX;

                    y = ChartHeight * (myPoint.y - Yorigin) / ScaleY;

                    g.DrawLine(blackPen, x0, y0, x, y);

                    g.FillEllipse(blackBrush, x0 - 2, y0 - 2, 4, 4);

                    g.FillEllipse(blackBrush, x - 2, y - 2, 4, 4);

                }

                prevPoint = myPoint;

            }



            //finally send graphics to browser
            return b;
            //MemoryStream memStream = new MemoryStream();
            // b.Save(memStream, ImageFormat.Jpeg);

        }

        ~LineChart()
        {

            g.Dispose();

            b.Dispose();

        }



    }

Sunday, September 19, 2010

How to get Error from application

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        Dim ErrStr As String
        ErrStr = "Some Error Has Occured in Websit" & vbCrLf
        ErrStr &= "Error Information Are Given Below" & vbCrLf
        ErrStr &= "---------------------------------------" & vbCrLf
        strError &= Server.GetLastError().ToString  +  vbCrLf
        SendMail("naween@gmail.com", "naween@live.com", "UnHandeled Exception Error", ErrStr)
 End Sub

How to Export DataGrid or GridView to PDF

Download dll from link 
http://sourceforge.net/projects/itextsharp/ 
 
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

protected void Button5_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);
        gvEmployee.AllowPaging = false; //gvEmployee is name of GridView
        gvEmployee.DataBind();
        gvEmployee.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();  
        
    }

How to Export DataGrid or GridView to Text

StringBuilder str = new StringBuilder();

for(int i=0;i<=ds.Tables[0].Rows.Count - 1; i++)
{
  for(int j=0;j<=ds.Tables[0].Columns.Count - 1; j++)
  {
      str.Append(ds.Tables[0].Rows[i][j].ToString());
  }

  str.Append("
");
}

Response.Clear();
Response.AddHeader("content-disposition", 
         "attachment;filename=FileName.txt");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.text";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = 
              new HtmlTextWriter(stringWrite);

Response.Write(str.ToString());
Response.End();

How to Export DataGrid or GridView to Word

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

myDataGrid.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End()

How to Export DataGrid or Gridview to Excel

Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

myDataGrid.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

Thursday, August 26, 2010

Programatically upload files to remote server

FtpWebRequest ftpRequest;
FtpWebResponse ftpResponse;
 
try
{
    //Settings required to establish a connection with the server
    this.ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://ServerIP/FileName"));
    this.ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
    this.ftpRequest.Proxy = null;
    this.ftpRequest.UseBinary = true;
    this.ftpRequest.Credentials = new NetworkCredential("UserName", "Password");
 
    //Selection of file to be uploaded
    FileInfo ff = new FileInfo("File Local Path With File Name"); //e.g.: c:\\Test.txt
    byte[] fileContents = new byte[ff.Length];
 
    //will destroy the object immediately after being used
    using (FileStream fr = ff.OpenRead())
    {
        fr.Read(fileContents, 0, Convert.ToInt32(ff.Length));
    }
 
    using (Stream writer = ftpRequest.GetRequestStream())
    {
        writer.Write(fileContents, 0, fileContents.Length);
    }
    //Gets the FtpWebResponse of the uploading operation
    this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse();
    Response.Write(this.ftpResponse.StatusDescription); //Display response
}
catch (WebException webex)
{
    this.Message = webex.ToString();
}

how to Download file from remote computer

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Net;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //base.OnLoad(e);
        string url = string.Empty;// Request.QueryString["DownloadUrl"];
        if (url == null || url.Length == 0)
        {
            url = "http://img444.imageshack.us/img444/6228/initialgridsq7.jpg";
        }
        //Initialize the input stream
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        int bufferSize = 1;
        //Initialize the output stream
        Response.Clear();
        Response.AppendHeader("Content-Disposition:", "attachment; filename=download.jpg");
        Response.AppendHeader("Content-Length", resp.ContentLength.ToString());
        Response.ContentType = "application/download";
        //Populate the output stream
        byte[] ByteBuffer = new byte[bufferSize + 1];
        MemoryStream ms = new MemoryStream(ByteBuffer, true);
        Stream rs = req.GetResponse().GetResponseStream();
        byte[] bytes = new byte[bufferSize + 1];
        while (rs.Read(ByteBuffer, 0, ByteBuffer.Length) > 0)
        {
            Response.BinaryWrite(ms.ToArray());
            Response.Flush();
        }
        //Cleanup
        Response.End();
        ms.Close();
        ms.Dispose();
        rs.Dispose();
        ByteBuffer = null;
    }
}

Wednesday, August 25, 2010

How to select Gridview Row in JavaScript

<script language="javascript" type="text/javascript">
var oldgridSelectedColor;

function setMouseOverColor(element)
{
    oldgridSelectedColor = element.style.backgroundColor;
    element.style.backgroundColor='yellow';
    element.style.cursor='hand';
    element.style.textDecoration='underline';
}

function setMouseOutColor(element)
{
    element.style.backgroundColor=oldgridSelectedColor;
    element.style.textDecoration='none';
}
</script>
protected void GridView1_RowDataBound(object sender, 
                    GridViewRowEventArgs e)
    {
        //check the item being bound is actually a DataRow, if it is, 
        //wire up the required html events and attach the relevant JavaScripts
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = 
                "javascript:setMouseOverColor(this);";
            e.Row.Attributes["onmouseout"] = 
                "javascript:setMouseOutColor(this);";
            e.Row.Attributes["onclick"] = 
            ClientScript.GetPostBackClientHyperlink
                (this.GridView1, "Select$" + e.Row.RowIndex);
        }
    }

Image Cache

Response.Clear()
        Response.ContentType = "image/jpg"
        Dim imgBytes As Byte() = CType(Cache("ImageBytes"), Byte())
        If imgBytes Is Nothing Then
        Using img As System.Drawing.Image = System.Drawing.Image.FromFile(Server.MapPath("TestImage.jpg"))
            Dim ms As IO.MemoryStream = New IO.MemoryStream()
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
            ms.Close()
            imgBytes = ms.GetBuffer()
            Cache("ImageBytes") = imgBytes
        End Using
        Response.OutputStream.Write(imgBytes, 0, imgBytes.Length)
        Response.Flush()
        Response.End()

Saturday, July 31, 2010

How to get Row Index at Row Command event of GridView

 If e.CommandName.Equals("Save") Then
            Dim gvr As GridViewRow = CType(CType(e.CommandSource, LinkButton).NamingContainer, GridViewRow)
            Dim RowIndex As Integer = gvr.RowIndex
End If

Thursday, July 1, 2010

Function to show pressed key in javascript

function show_key(e)
{ 
 
KeyID= Window.Event ? e.KeyCode : e.Which;
switch(KeyID)

   {

      case 16:

      document.Form1.KeyName.value = "Shift";

      break; 

      case 17:

      document.Form1.KeyName.value = "Ctrl";

      break;

      case 18:

      document.Form1.KeyName.value = "Alt";

      break;

      case 19:

      document.Form1.KeyName.value = "Pause";

      break;

      case 37:

      document.Form1.KeyName.value = "Arrow Left";

      break;

      case 38:

      document.Form1.KeyName.value = "Arrow Up";

      break;

      case 39:

      document.Form1.KeyName.value = "Arrow Right";

      break;

      case 40:

      document.Form1.KeyName.value = "Arrow Down";

      break;
   }

}

Wednesday, June 30, 2010

Function to Select or Deselect all checkbox in a gridview through javascript

<script language="javascript" type="text/javascript" >
function SelectAll(SelBtn)
     {
          var gvET = document.getElementById("GridView1"); 
             var rCount = gvET.rows.length;
             var btnSel = SelBtn.value;
             var rowIdx;
             // check the Page Count is greater than 1 then rowindex will start from 2 else 1
             if(document.getElementById("hidgridpagecount").value>1)
             {
                  rowIdx=2;
             }
             else
             {
                  rowIdx=1;
             }
             for (rowIdx; rowIdx<=rCount-1; rowIdx++)
             {
                  var rowElement = gvET.rows[rowIdx];
                  var chkBox = rowElement.cells[0].firstChild;
                  if (btnSel == 'Select All')
                  {
                       chkBox.checked = true;
                  }
                  else
                  {
                       chkBox.checked = false;
                  }
             }
             if (btnSel == 'Select All')
             {
                  document.getElementById('btnSelAll_Top').value ="Deselect All";
                  document.getElementById('btnSelAll_Bot').value ="Deselect All";
             }
             else
             {
                  document.getElementById('btnSelAll_Top').value ="Select All";
                  document.getElementById('btnSelAll_Bot').value ="Select All";
             }
             return false;
     }
</script>

Function to Get GridView Row And Column through JavaScript

<script language="javascript" type="text/javascript">
var gridViewCtlId = '<%=ctlGridView.ClientID%>';
    var gridViewCtl = null;
    var curSelRow = null;
    var curRowIdx = -1;
    function getGridViewControl()
    {
        if (null == gridViewCtl)
        {
            gridViewCtl = document.getElementById(gridViewCtlId);
        }
    }
    
    function onGridViewRowSelected(rowIdx)
    {
        var selRow = getSelectedRow(rowIdx);
        if (null != selRow)
        {
            curSelRow = selRow;
            var cellValue = getCellValue(rowIdx, 0);
            alert(cellValue);
        }
    }
    
    function getSelectedRow(rowIdx)
    {
        return getGridRow(rowIdx);
    }
    
    function getGridRow(rowIdx)
    {
        getGridViewControl();
        if (null != gridViewCtl)
        {
            return gridViewCtl.rows[rowIdx];
        }
        return null;
    }
    
    function getGridColumn(rowIdx, colIdx)
    {
        var gridRow = getGridRow(rowIdx);
        if (null != gridRow)
        {
            return gridRow.cells[colIdx];
        }
        return null;
    }
    
    function getCellValue(rowIdx, colIdx)
    {
        var gridCell = getGridColumn(rowIdx, colIdx);
        if (null != gridCell)
        {
            return gridCell.innerText;
        }
        return null;
    }
</script>
  

Wednesday, June 23, 2010

Rename Table's Column Name in Oracle

SQL> desc phone;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 PHONE_ID                                  NOT NULL NUMBER(10)
 FK_PHONE_ACCOUNT_ID                       NOT NULL NUMBER(10)
 PHONE_AREACODE                            NOT NULL VARCHAR2(5)
 PHONE_NUMBER                              NOT NULL NUMBER(10)
 PHONE_CITY                                NOT NULL VARCHAR2(40)
 FK_PHONE_PLAN_ID                          NOT NULL NUMBER(5)
 FK_PHONE_USAGE_ID                         NOT NULL NUMBER(5)
 PHONE_ENABLED                             NOT NULL NUMBER(1)
 FK_EMPLOYEEID                             NOT NULL NUMBER(10)
 COMPANY_AMOUNT                                     NUMBER(10,2)


SQL> alter table phone rename column PHONE_CITY to FK_IIL_COMP_LOC_ID;
SQL> Desc Phone;

 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 PHONE_ID                                  NOT NULL NUMBER(10)
 FK_PHONE_ACCOUNT_ID                       NOT NULL NUMBER(10)
 PHONE_AREACODE                            NOT NULL VARCHAR2(5)
 PHONE_NUMBER                              NOT NULL NUMBER(10)
 FK_IIL_COMP_LOC_ID                        NOT NULL VARCHAR2(40)
 FK_PHONE_PLAN_ID                          NOT NULL NUMBER(5)
 FK_PHONE_USAGE_ID                         NOT NULL NUMBER(5)
 PHONE_ENABLED                             NOT NULL NUMBER(1)
 FK_EMPLOYEEID                             NOT NULL NUMBER(10)
 COMPANY_AMOUNT                                     NUMBER(10,2)

Monday, June 14, 2010

Example for Allowing Only Numric in a textbox on Client side

<asp:TextBox ID="txt_tenderno"  onkeydown="return onKeyPressBlockNumbers(event)" onFocus="this.style.background ='yellow'" onBlur="this.style.background='white'" runat="server" ></asp:TextBox>
function onKeyPressBlockNumbers(e)
{
 var key = window.event ? e.keyCode : e.which;
 var keychar = String.fromCharCode(key);
 reg = /\d/;
 return !reg.test(keychar);
}
-----------------OR---------------------
<asp:TextBox ID="txt_tenderno"  onkeydown="return numeric(event)" onFocus="this.style.background ='yellow'" onBlur="this.style.background='white'" runat="server" ></asp:TextBox>
function numeric(e) {
var key = window.event ? e.keyCode : e.which;
   return ((key == 8) || (key > 47 && key < 58));
}


 

To get Grid View Rows in Javascript

<script language="javascript" type="text/javascript">
var gridViewCtlId = '<%=ctlGridView.ClientID%>';
    var gridViewCtl = null;
    var curSelRow = null;
    var curRowIdx = -1;
    function getGridViewControl()
    {
        if (null == gridViewCtl)
        {
            gridViewCtl = document.getElementById(gridViewCtlId);
        }
    }
    
    function onGridViewRowSelected(rowIdx)
    {
        var selRow = getSelectedRow(rowIdx);
        if (null != selRow)
        {
            curSelRow = selRow;
            var cellValue = getCellValue(rowIdx, 0);
            alert(cellValue);
        }
    }
    
    function getSelectedRow(rowIdx)
    {
        return getGridRow(rowIdx);
    }
    
    function getGridRow(rowIdx)
    {
        getGridViewControl();
        if (null != gridViewCtl)
        {
            return gridViewCtl.rows[rowIdx];
        }
        return null;
    }
    
    function getGridColumn(rowIdx, colIdx)
    {
        var gridRow = getGridRow(rowIdx);
        if (null != gridRow)
        {
            return gridRow.cells[colIdx];
        }
        return null;
    }
    
    function getCellValue(rowIdx, colIdx)
    {
        var gridCell = getGridColumn(rowIdx, colIdx);
        if (null != gridCell)
        {
            return gridCell.innerText;
        }
        return null;
    }
</script>

Thursday, June 10, 2010

Change Default Formate in Oracle

ALTER SESSION SET NLS_DATE_FORMAT='MM/DD/YYYY';

Tuesday, June 8, 2010

ClickOnce Deployment In Visula Basic 2008 Express Edition

I see. well yes you can do this, its called ClickOnce deployment. Take a look at this:


if you have the full version of VS.NET, then you could make your own installer and has more flexibility on what you can do but since its the express version, you get ClickOnce deployment

Monday, June 7, 2010

Listing Files in Dictionary

 Private Sub ListFilesInDictionay(ByVal sStartDir As String, ByRef MyDict As Dictionary(Of Integer, String))
        Dim OutDir As DirectoryInfo = New DirectoryInfo(sStartDir)
        If OutDir.Exists Then
            Dim MyFileNum As Integer = 1
            For Each OurFile As FileInfo In OutDir.GetFiles
                MyDict.Add(MyFileNum, OurFile.Name)
                MyFileNum += 1
            Next
        End If
    End Sub

Tuesday, June 1, 2010

To Show Controls those are not validated as yellow background

on the page_prerender event paste below scratched code

foreach (BaseValidator valControl in Page.Validators)
{
WebControl assControl = (WebControl)Page.FindControl(valControl.ControlToValidate);
if (!valControl.IsValid)
assControl.BackColor = System.Drawing.Color.Yellow;
else
assControl.BackColor = System.Drawing.Color.White;
}
}

Monday, May 31, 2010

To Change the Image Randomly On Post Back

use a image control with the name imgRandom and Paste the below scratched code on page Load event

Random rnd = new Random();
switch (rnd.Next(3))
{
case 0:
imgRandom.ImageUrl = “Picture1.gif”;
imgRandom.AlternateText = “Picture 1”;
break;
case 1:
imgRandom.ImageUrl = “Picture2.gif”;
imgRandom.AlternateText = “Picture 2”;
break;
case 2:
imgRandom.ImageUrl = “Picture3.gif”;
imgRandom.AlternateText = “Picture 3”;
break;
}

Functin for Moving Title of Page in JavaScript


<script type="text/javascript">
    var rev = "fwd";
    function titlebar(val) {
        var msg = "Welcome To IndiaMART WebERP";
        var res = " ";
        var speed = 100;
        var pos = val;

        //msg = "   |--- " + msg + " ---|";
        var le = msg.length;
        if (rev == "fwd") {
            if (pos < le) {
                pos = pos + 1;
                scroll = msg.substr(0, pos);
                document.title = scroll;
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
            else {
                rev = "bwd";
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
        }
        else {
            if (pos > 0) {
                pos = pos - 1;
                var ale = le - pos;
                scrol = msg.substr(ale, le);
                document.title = scrol;
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
            else {
                rev = "fwd";
                timer = window.setTimeout("titlebar(" + pos + ")", speed);
            }
        }
    }

    titlebar(0);
</script>

Function To Validate Only Alphabet allowed in JavaScript

function fnAlphabet(e)
{
    var code = e.keyCode ? event.keyCode : e.which ? e.which : e.charCode;
    //alert(code);
    if ((code >= 65 && code <= 90)||(code >= 97 && code <= 122) || code==46 || code==8 || code==17 || code==127 || code==9 || code==16 || code==37 || code==38 || code==39 || code==40)
    {
        checknos = true;
        return (checknos);
    }
    else
    {
        checknos= false;           
        alert("Only Alphabates Allowed !");       
        return (checknos);        }
}

Function To Validate Only Number Allowed in JavaScript

function fnNotAlphabet(e)
{
    var code = e.keyCode ? event.keyCode : e.which ? e.which : e.charCode;       
    //Code Explanation{ 0-9, 45=Insert, 13=Enter, 08=Backspace, 09=Tab}
    if ((code >= 48 && code <= 57)||(code == 45 || code == 13 || code == 08 || code == 09))
    {
        checknos = true;
        return (checknos);
    }
    else
    {
        checknos= false;
        alert("Only Number Allowed !");   
        return (checknos);
    }
}

Function To Validate Mobile No. in JavaScript

function validateMobileNumber(idMobileNumber, idColumnLabelToHighlight)
{
    var varMobileNumber = document.getElementById(idMobileNumber).value;
    if(isNaN(varMobileNumber) || varMobileNumber.indexOf(" ")!=-1)
    {
        alert("Mobile Number : Enter numeric value");
        document.getElementById(idColumnLabelToHighlight).style.color="#ff0000";       
        return false; 
    }
    if (varMobileNumber.length != 10 )
    {
        alert("Mobile Number : Enter 10 characters valid mobile number without 0");
        document.getElementById(idColumnLabelToHighlight).style.color="#ff0000";       
        return false;
    }
   
    if (varMobileNumber.charAt(0)!=8 && varMobileNumber.charAt(0)!=9)
    {
     
        alert("Mobile Number : The number can only start with 8 or 9.");
        document.getElementById(idColumnLabelToHighlight).style.color="#ff0000";       
        return false
    }
   
    document.getElementById(idColumnLabelToHighlight).style.color="#000000";
    return true;
}

Function To Check Adult in JavaScript

function checkIfAdult(idYear, idMonth, idDay, idColumnLabelToHighlight)
{
    var varYear = document.getElementById(idYear).value;
    var varMonth = document.getElementById(idMonth).value;
    var varDate = document.getElementById(idDay).value;

    var toDay = new Date();
    var AgeToCompare = new Date();
   
    AgeToCompare.setDate(varDate);
    AgeToCompare.setMonth((parseInt(varMonth)-1));
    AgeToCompare.setFullYear(varYear);
    //alert("Diff : ");
    var currentYear = toDay.getFullYear();
    var toCompareYear = AgeToCompare.getFullYear();
    //alert("Inside");
    var currentMonth = toDay.getMonth();
    var toCompareMonth = AgeToCompare.getMonth();
    //alert("Inside");

    var currentDay = toDay.getDate();
    var toCompareDay = AgeToCompare.getDate();
    //alert("Inside");
   
    var toReturn = true;
       
    //alert("Diff : " + (currentYear - toCompareYear)) ;
    document.getElementById(idColumnLabelToHighlight).style.color="#000000";   
    if( (currentYear - toCompareYear)  > 17 )   
    {
        //alert("> 17");
        toReturn = true;
    }
    else if( (currentYear - toCompareYear)  == 17 )   
    {
        //alert("= 17");
       //alert("Diff : " + (currentMonth - toCompareMonth)) ;
        if( (currentMonth - toCompareMonth)  > 0 )   
        {
            toReturn = true;
        }
        else if( (currentMonth - toCompareMonth)  == 0 )   
        {
            //alert("Diff : " + (currentDay - toCompareDay)) ;
            if( (currentDay - toCompareDay)  > 0 ) 
            { 
                toReturn = true;
            }   
            else
            {
                toReturn = false;
            }   
        }
        else
        {
             toReturn = false;
        }  
        document.getElementById(idColumnLabelToHighlight).style.color="#000000";
    }
    else
    {
        toReturn = false;
    }
    if(toReturn == false)
    {
        alert("Date Error : Only adults can book use this.");
        document.getElementById(idColumnLabelToHighlight).style.color="#ff0000";
        return false;
    }
    return toReturn;
}

Sending Mail With ASP.NET

One of the common functionalities used in Web development is sending email from a Web page. A common use of sending email from a Web page is allowing site visitors to fill in comments via an HTML form and send them to the Webmaster. The .NET Framework makes the task of sending email from a Web page relatively simple. In order to send an email from an ASP.NET Web page you need to use the SmtpMail class found in the System.Web.Mail namespace, which contains a static method Send.
Sending Email 
The namespace that needs to be imported to send an email is the System.Web.Mail namespace. We use the SmtpMail and MailMessage classes of this namespace for this purpose. The MailMessage class provides properties and methods for constructing an email message. To start, open a Web Forms page, drag a Button control on to the form, switch to code view and paste the following code.

Imports System.Web.Mail
'namespace to be imported

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
Dim mailMessage As New MailMessage()
'creating an instance of the MailMessage class
mailMessage.From = "xyz@mydomain.com"
'senders email address
mailMessage.To = "abc@sendersemail.com"
'recipient's email address
mailMessage.Cc = "carboncopy@sendersemail.com"
'email address of the Cc recipient
mailMessage.Bcc = "blindcarboncopy@sendersemail.com"
'email address of the Bcc recipient
mailMessage.Subject = "Hello"
'subject of the email message
mailMessage.BodyFormat = MailFormat.Text
'message text format. Can be text or html
mailMessage.Body = "This tutorial is sending email with an ASP.NET app."
'message body
mailMessage.Priority = MailPriority.Normal
'email priority. Can be low, normal or high
SmtpMail.SmtpServer = "mail.yourserver.com"
'mail server used to send this email. modify this line based on your mail server
SmtpMail.Send(mailMessage)
'using the static method "Send" of the SmtpMail class to send the mail
Response.Write("Mail sent")
'message stating the mail is sent
End Sub
The above code sends an email when the button is clicked. That's fine for the purpose of learning but when you have a feedback form on your Web site with textboxes, labels, etc, you need to slightly modify the above code. The following is the complete, functional code for an ASP.NET page that sends an email to the Webmaster of the site.
To start, drag seven labels, six textboxes and two buttons on to the Web forms page designer. The user interface for this sample can be found at the bottom of this page. The modified code looks as follows:
Imports System.Web.Mail

Private Sub SendMail_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles SendMail.Click
Dim mailMessage As New MailMessage()
mailMessage.From = TextBox1.Text
mailMessage.To = "admin@startvbdotnet.com"
'you also can set this to TextBox2.Text
mailMessage.Cc = TextBox3.Text
mailMessage.Bcc = TextBox4.Text
mailMessage.Subject = TextBox5.Text
mailMessage.BodyFormat = MailFormat.Text
mailMessage.Body = TextBox6.Text
'textbox6 TextMode property is set to MultiLine
mailMessage.Priority = MailPriority.Normal
SmtpMail.SmtpServer = "mail.yourserver.com"
'mail server used to send this email. modify this line based on your mail server
SmtpMail.Send(mailMessage)
Label6.Text = "Your mail was sent"
'message stating the mail is sent
End Sub

Private Sub Reset_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Reset.Click
TextBox1.Text = " "
TextBox2.Text = " "
TextBox3.Text = " "
TextBox4.Text = " "
TextBox5.Text = " "
TextBox6.Text = " "
'resetting all the value to default i.e null
End Sub

Sunday, May 30, 2010

To Prevent Click Again and Again During Processing....

-------------- On the Page Load Event --------------
Me.btn_Save.Attributes.Add("onclick", "if (confirm('Are You For Save?')){this.value='Please wait...';this.disabled=true;} else {return false;}" & ClientScript.GetPostBackEventReference(Me.btn_Save, "Save"))

Saturday, May 29, 2010

To Do Properly Work AJAX with Asp.net 2005

Download ASPAJAXSETUP 2.0 over Net and install it.
Add a  tab on Toolbar by  the name Ajax Extender.
Right Click on your Toolbar and click on Choose Items. Select Update Panel, Script Manager, Update Progress.

In Web.Config Add Following........

<httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
           <add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

</httpHandlers>
           
<runtime>
       <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31BF3856AD364E35"/>
                <bindingRedirect oldVersion="3.5.0.0" newVersion="1.0.61025.0"/>
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31BF3856AD364E35"/>
                <bindingRedirect oldVersion="3.5.0.0" newVersion="1.0.61025.0"/>
            </dependentAssembly>
        </assemblyBinding>
    </runtime>         
Now get enjoy with AJAX................

Generate Excel Report

Public Sub GenExlReport(ByVal P_DataSet As Data.DataSet, ByRef P_refdatagrid As DataGrid, ByRef P_HttpResponse As Web.HttpResponse, ByRef P_Page As Page)
        If P_DataSet Is Nothing Then P_HttpResponse.Write("Error in generation of Exl Report") : Exit Sub
        Dim DSList As New Data.DataSet
        Dim MyView As New Data.DataView
        Dim stringWrite As New System.IO.StringWriter
        Dim htmlWrite As New HtmlTextWriter(stringWrite)
        Try
            DSList = P_DataSet
            MyView.Table = DSList.Tables(0)
            With P_refdatagrid
                .DataSource = MyView
                .DataBind()
                .Visible = True
            End With
            With P_HttpResponse
                .Clear()
                .AddHeader("content-disposition", "attachment;filename=FileName.xls")
                .Charset = String.Empty
                .Cache.SetCacheability(HttpCacheability.NoCache)
                .ContentType = "application/vnd.xls"
            End With
            P_refdatagrid.RenderControl(htmlWrite)
            P_HttpResponse.Write(stringWrite.ToString())
            P_refdatagrid.Visible = False
            P_HttpResponse.End()
        Catch ex As Exception
            P_HttpResponse.Write("Error in generation of Exl Report")
        Finally
            DSList.Dispose() : MyView.Dispose()
            stringWrite.Dispose() : htmlWrite.Dispose()
        End Try
End Sub