You are viewing [info]achu8's journal

achu8's Journal
 
[Most Recent Entries] [Calendar View] [Friends]

Below are the 20 most recent journal entries recorded in achu8's LiveJournal:

    Saturday, May 22nd, 2010
    4:23 pm
    BSNL Broadband Username and Password
    Couple of days back, I reset my modem as I forgot my password to enter the router configuration. Later I was not able to connect to the internet as the modem was not configure with the username and password ( inside advanced setup) and I don't know the username and password. Today I spent 90 mins to get it from BSNL office. It doesn't really takes such a long time to do that. The username and password will be as below:

    If your landline number is 044-123456789, 
              username : XX44123456789
    XX - I belive, it should be the first 2 letters of the registered name.


    Your password will always be password

    Sunday, February 7th, 2010
    5:08 pm
    Export Excel Data to SQL Server
    I had a requirement to import 8000+ data in excel sheet to be imported in SQL Server database table. After browsing about 8 sites, I found a way to do this using following method:

    INSERT INTO [dbo].[TableName]  ( [Column1], [Column2])

    SELECT

    * From OpenRowSet('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=f:\myExcelSheet.xls' , [Sheet1$])


    Before that, we need to execute the below queries to make it work:

    sp_configure

    sp_configure 'show advanced options', 1
    reconfigure

    sp_configure 'Ad Hoc Distributed Queries', 1

    reconfigure


    The above query enables the Ad Hoc Distributed Queries which then enables us to execute OpenRowSet statement.

    Current Mood: accomplished
    Thursday, October 1st, 2009
    11:02 pm
    First in Client Side Development
    In last 30 days of active posting, I reached 1st place of giving answers. Here it is:


    Monday, September 21st, 2009
    10:12 pm
    Contributor of asp.net
    Today (21/09/2009), I became the contributor of asp.net forums. I've attained the 3rd level. A long way to go.

    Current Mood: amused
    Wednesday, June 17th, 2009
    1:29 pm
    Random String Generation
    The following code is used to generate random string using c#:

    Random rnd = new Random(DateTime.Now.Millisecond);
                                                         // This Random class is used to generate Next Random Double value (between 0.0 and 1.0) which    multiplies with 26 below:

    private object GetRandomString()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 6; i++)    // number of random characters ( i ) you determine here
            {
                sb.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rnd.NextDouble() + 65))));
            }
            return sb.ToString();
        }

    Wednesday, May 27th, 2009
    9:57 pm
    Prevent going to Previous Page when Backspace is hit
    In most of the web application where transaction happens, we need to concentrate on few things. Like when hitting backspace, the page sometime will go to the previous page and brings the old values. Its not the user's mistake to hit the backspace when he uses it. When the cursor is placed on any part of the screen(not controls) and hit backspace, it will go to previous page. This can be prevented by writing a javascript in <head> tag.

    <head>
    <script type="text/javascript">
        function killBackSpace(e)
        {
            e = e? e : window.event;
            var t = e.target? e.target : e.srcElement? e.srcElement : null;
            if(t && t.tagName && (t.type && /(password)|(text)|(file)/.test(t.type.toLowerCase())) || t.tagName.toLowerCase() == 'textarea')
            return true;
            var k = e.keyCode? e.keyCode : e.which? e.which : null;
            if (k == 8){
            if (e.preventDefault)
            e.preventDefault();
            return false;

        };
        return true;
    };
    if(typeof document.addEventListener!='undefined')
    document.addEventListener('keydown', killBackSpace, false);
    else if(typeof document.attachEvent!='undefined')
    document.attachEvent('onkeydown', killBackSpace);
    else{
    if(document.onkeydown!=null){
    var oldOnkeydown=document.onkeydown;
    document.onkeydown=function(e){
    oldOnkeydown(e);
    killBackSpace(e);
    };}
    else
    document.onkeydown=killBackSpace;

    }
        </script>

    </head>

    Sunday, April 19th, 2009
    1:49 pm
    Sql Server Query
    To select all the Database names from the Server, the query is:

    SELECT dbid, name FROM master.dbo.sysdatabases

    It will list all the Database name and Database ID from the Server.


    To select all the table names from a Database, the query is:


    Use DatabaseName
    ;
    SELECT ID, Name from sysobjects where xtype = 'u'

    It will list all the User Tables from the selected Database.


    To select only Column Names for a table, the query is:

    SELECT Column_Name[ColumnName] FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + sTableName + "' ORDER BY ORDINAL_POSITION

    This query will list all the column name for the specified - "sTableName". There are other fields as well, like DataType, IsNullable, OrdinalPosition etc which can be selected depending upon the requirements you want.


    To check if a column is Primary Key, the query is:

    SELECT Column_Name FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE OBJECTPROPERTY(OBJECT_ID(QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1 and Table_Name = '" + sTableName + "'"


    This will select the column name(s) which are primary key in the specified table - "sTableName".


    To check if a column is Foreign Key, the query is:

    SELECT Column_Name FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE WHERE OBJECTPROPERTY(OBJECT_ID(QUOTENAME(CONSTRAINT_NAME)), 'Is
    ForeignKey') = 1 and Table_Name = '" + sTableName + "'"

    This will select the column name(s) which are foreign key in the specified table - "sTableName".

    Thursday, March 26th, 2009
    10:49 pm
    JQuery is Amazing
    Today I tried my first script in JQuery with Visual Studio. It quite different from javascript, but still good to write scripts. A long way to go learning this new language. Will learn the tricks and post tips using JQuery with Visual Studio.

    ~ Its all about coding.
    Tuesday, December 16th, 2008
    10:39 am
    Find Controls in Tab Container using JavaScript
    If you use Tab Container and wanna find the ClientID or the Value of the Controls inside the Tab Container, here is the method to find it. It is different from normal method of finding the controls.

    <body>
        <form id="form1" runat="server">

       <script type="text/javascript">
        function call()

       
    {
            var v = $get("<%= btn.ClientID%>");
     
      // Gives the Object of the Control.
            var b = $get("<%= btn.ClientID%>").value;  // Gives the value of the Object.
            alert(v);
            alert(b);
        }
            </script>


            <div>
                <asp:ScriptManager ID="ScriptManager1" runat="server">
                </asp:ScriptManager>
                <cc1:TabContainer ID="TabContainer1" runat="server">
                    <cc1:TabPanel ID="t1" runat='Server' HeaderText="Hello">
                        <ContentTemplate>
                            <asp:Button ID="btn" runat="server" Text="Hello" OnClientClick="call()" />
                        </ContentTemplate>
                    </cc1:TabPanel>
                    <cc1:TabPanel ID="TabPanel1" runat='Server' HeaderText="Test">
                        <ContentTemplate>
                            <asp:Button ID="Button1" runat="server" Text="Hello" OnClientClick="call()" />
                        </ContentTemplate>
                    </cc1:TabPanel>
                </cc1:TabContainer>
            </div>
        </form>
    </body>


    Here JavaScript is placed inside the Form Tag since only the portion inside the <form> tag is parsed and executed.

    Monday, December 15th, 2008
    1:08 pm
    JavaScript Timer
    Hello,

                It is possible to set Timer in JavaScript and here is a sample that demonstrates it. A label which displays a text on Client Side and disappears after N seconds.

    function ShowError()
        {
            document.getElementById('lbl').innerHTML = "Display Error Here";         // Error is displayed on Client Click.
            setTimeout("Hide()", 3000);                                                              // Calls the Hide() method after 3 seconds.
            return false;
        }
        function Hide()
        {
            document.getElementById('lbl').innerHTML = "";                                         // Clears the Lable Text
        }


    The above script can be called using any control. In this sample code, I've used Button control:


    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" OnClientClick="return ShowError()" Text="Button" />

    11:00 am
    Fix GridView Header
    Here is the Code snippet to fix the GridView header.
    Works for IE6 and IE7



    Set the Div's class = scrollTable

    <div id="Div1" class="scrollTable" runat="server" style="height: 200px; width: auto; overflow: auto; text-align: center;">
    <asp:GridView ID="gr1" runat="server" Width="300px" Height="200px" AutoGenerateColumns="False">

    ...............................
    </GridView>

    Thursday, November 6th, 2008
    12:54 pm
    Bind the SelectedValue of DropDownList inside the GridView
    Hello,

               This is a demo to Bind the SelectedValue of the DropDownList inside the GridView. Most of the people use DropDownList inside the GridView <EditItemTemplate>. When Editing the GridView, the DropDownList is rebinded and the first value from the DataBase appears to be the SelectedValue of the DropDownList. This make confusion of knowing the actual value that was present. I've tried a small demo and would like to share here.


    Default.aspx:

    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" OnRowEditing="GridView1_RowEditing">
                    <Columns>
                        <asp:TemplateField Visible="False">
                            <ItemTemplate>
                                <asp:Label ID="lblId" runat="server" Text='<%# Eval("UserId") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                         <EditItemTemplate>
                            <asp:DropDownList ID="ddl" runat="server" DataTextField="UserName" DataValueField="UserId" Visible="true" />
                        </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="lblName" runat="server" Text='<%# Eval("UserName") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
        </form>
    </body>


    Default.aspx.cs:

    public partial class DDLIssue : System.Web.UI.Page
    {
        Class1 cc = new Class1();
        static int ri;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridView1.DataSource = cc.GetData();                //<-- Binding the GridView using DataSet returned from the Class cc
                GridView1.DataBind();
            }
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            DataSet ds = cc.GetData();
            GridView1.EditIndex = e.NewEditIndex;
            GridView1.DataSource = cc.GetData();
            GridView1.DataBind();
            ri = e.NewEditIndex;
            int id = 0;
            DropDownList ddlb = (DropDownList)GridView1.Rows[ri].FindControl("ddl");
            ddlb.DataSource = cc.GetData();
            int sId = int.Parse(ds.Tables[0].Rows[ri]["UserId"].ToString()); //<-- Get the UniqueID(UserId) of the SelectedRow using the ds
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)          //<-- Iterate through the Loop
            {
                string selected = ((Label)GridView1.Rows[i].FindControl("lblId")).Text.ToString();  //<-- Get the Selected Text (Label Value)
                int k = int.Parse(selected);  //<-- Convert it to Integer
                if (sId == k)             
       //<-- Compare the SelectedRowId(UserId - UniqueID) = GridView's Label Id(UserId - UniqueID)
                {
                    id = i;       //  <-- Assign it to an Integer
                    break;
                }
            }       
            ddlb.DataBind();

            ddlb.SelectedIndex = id;          //   <-- Bind the DDL with the id as Index.
        }
    }


    Using the above code, you can bind the SelectedValue into the DropDownList.

    BTW: There are many ways to get the SelectedValue. This is the way which I tried it of my OWN.

    Monday, November 3rd, 2008
    12:18 pm
    Select and Highlight the TextBox using JavaScript
    The below code snippet is used to highlight the text in the TextBox once the TextBox is focused. Normally we need to focus a text box when a new value has to be entered or to show duplicate value is entered and highlight the TextBox.

    In C#, we need to focus the TextBox first.


    On any event, eg. Button1_Click event, you will focus on the TextBox like

    protected void Button1_Click(object sender, EventArgs e)
    {

          (When duplicate text has been entered and you want to show the user that the text is duplicated, you can highlight the textbox and  show using......)
          SetFocus(TextBox1);    --> This will set focus on the TextBox
          TextBox1.Attributes.Add("onfocusin", "select();");       --> This will highlight the Text in the TextBox
    }

    The above code will highlight the text in the TextBox1.

    If you also want to show a different color for the textbox when text is duplicated, you can change the BackGroundColor of the Text to your desired color

    Write the below code on the event where you want:

    TextBox1.Attributes.Add("onfocusin", "select(); "this.style.backgroundColor ='Yellow';");



    Thursday, October 9th, 2008
    3:55 pm
    Page Load twice in ASP.NET
    For more than a week I was struggling with an issue, i.e., Page is loaded twice in my asp.net application. The scenario is, I have a Grid View. Dynamically I add a row in order to insert a record or single click on the row to edit the record. I have a "Save" Image Button inside the Grid View. It is at the right end of the Grid View. When I click on the "Save" Image Button, the Page Loaded twice. Searching so many forums didn't help me. One of my colleagues noted the following error which caused the problem:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    ((CheckBox)e.Row.FindControl("chkSelect")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("chkSelect")).ClientID + "')");
                }


              
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';";

                    e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
                   string
    jsCommand = string.Format("if ({2} != {1}) __doPostBack('{0}','Edit${1}')", GridView1.ID, e.Row.RowIndex, GridView1.EditIndex);

                    foreach (TableCell c in e.Row.Cells)
                    {
                        if (c == e.Row.Cells[1] |
    c == e.Row.Cells[8])
                        {
                        }
                        else
                        {
                            c.Attributes["onclick"] +=
    jsCommand;
                        }
                    }
                }
         }
         catch(Exception ex)
         {
              throw ex;
         }
    }



    c == e.Row.Cells[8]  - I was missing this code in my application.

    The reason behind this code is, I have the "Save" Image button in 8th Cell(Column) of the GridView
    . So earlier, when this code was not present, When ever I click, the jsCommand will do a post back. I didn't add the 8th cell in the empty loop. That is the reason it caused me 2 page loads.

    Tuesday, October 7th, 2008
    11:55 am
    To check Foreign Key Dependents before deleting
    I've written a procedure to check the foreign key dependents in a table before deleting the record in asp.net. For eg. You have records in a Page which shows the data from the Master table. The data can be referred in any other page, which will become the Foreign Key of the Master Table, so we should not be able to delete that record as dependent record exists in other table(s). This procedure will check that. 3 parameters should be passed from aspx page.

    1. Table Name (Eg: Employee)
    2. Foreign Key (Eg: EmployeeId)
    3. Value (Eg: Like EmployeeId = 8)


    CREATE   procedure dbo.USP_CheckDependents
    @TName varchar(30),   -- Table Name
    @Param varchar(20),    -- Foreign Key Field
    @Value int                       -- Value of the Foreign Key Field

    as
    Begin
        declare @TableNames Table(Table_Name varchar(30))
       
        declare @DependantTables varchar(30)
        declare @SQL nvarchar(1000)
        declare @SQL1 nvarchar(1000)
        declare @SQL2 nvarchar(1000)

       
        declare @id int
       
        insert into  @TableNames (Table_Name)(select  distinct a.table_name
        from information_schema.constraint_table_usage a , information_schema.constraint_column_usage b
        where a.constraint_name=b.constraint_name and a.constraint_name in (
        select constraint_name
        from information_schema.referential_constraints
        where unique_constraint_name =(
        select constraint_name   from information_schema.table_constraints
        where table_name =@TName and constraint_type ='PRIMARY KEY')))
       
        declare CursorCity cursor read_only
        for select * from @TableNames
        open CursorCity
        fetch next from CursorCity into @DependantTables

        while @@Fetch_Status = 0
        begin

        select @id = @Value

       
        begin
           select @SQL = 'select count('+@Param+') As '+@DependantTables+' from '+@DependantTables+ ' where '+@Param+ ' = ' +str(@id)
          exec sp_executesql @SQL
        End
       
        fetch next from CursorCity into @DependantTables
       
        end
        close CursorCity
        deallocate CursorCity

    End

    To Execute the Procedure:

    exec 'Employee', 'EmployeeId',8

    Now you can find the Tables which has the count of the field which has reference.

    Explaination:
    insert into  @TableNames (Table_Name)(select  distinct a.table_name
        from information_schema.constraint_table_usage a , information_schema.constraint_column_usage b
        where a.constraint_name=b.constraint_name and a.constraint_name in (
        select constraint_name
        from information_schema.referential_constraints
        where unique_constraint_name =(
        select constraint_name   from information_schema.table_constraints
        where table_name =@TName and constraint_type ='PRIMARY KEY')))


    This will create a Temporary Table and insert all the Table Name which has foreign Key Relationship of the given Table. @TName is the Table Name. If you give 'Employee' (please use Single Quotes) in the place of @TName, it will list the tables which contains the reference.


    declare CursorCity cursor read_only
        for select * from @TableNames
        open CursorCity
        fetch next from CursorCity into @DependantTables

        while @@Fetch_Status = 0
        begin

        select @id = @Value   -- Assigning  @Value to @id

       
        begin
           select @SQL = 'select count('+@Param+') As '+@DependantTables+' from '+@DependantTables+ ' where '+@Param+ ' = ' +str(@id)
          exec sp_executesql @SQL
        End
       
        fetch next from CursorCity into @DependantTables
       
        end
        close CursorCity
        deallocate CursorCity

    End



    I've used Cursor here, because it will loop through all the Table Names in the Temporary Table and fetch the count of fields that consists of records. For example, if we say EmployeeId is referred to 2 tables - Department and Salary. Executing the procedure will display result as follow:

    Department
    2

    Salary
    1


    So this shows that EmployeeId is referred to 2 rows in Department and 1 row in Salary.

    Using the above result, in aspx page, you can use any of the Data class and display error message telling that 'You cannot delete the record as dependent record exists'


    The reason behind this checking is, once you delete the master record and still it is referred in any other page as child record, next time when you try to access the record, it will throw an exception and you cannot execute your page.

    You can use this procedure in order to minimize your errors in future.


    Thanks and Regards,
    Achutha Krishnan Bathey

    Tuesday, September 30th, 2008
    2:13 pm
    Confirm message for Deleting record(s) in Grid View
    Java Script to show a Confirm Dialog box before deleting record(s) in Grid View.



    This Script should be written in aspx page:

    <script type="text/javascript" language="javascript">
        function confirmMessageDelete(frm)
        {
            for(i = 0; i < frm.length; i++)
            {
                if(frm.elements[i].checked)
                {
                    return confirm("Are you sure you want to delete the selected record(s)?");
                    return true;
                }           
            }       
            document.getElementById('lblMessage').innerHTML = "Select at least one record to delete";
           
            return false;
        }
        </script>


    You should have the below code for your Delete Button:

    <asp:Button ID="btnDelete" runat="server" OnClientClick="return confirmMessageDelete(this.form)"  OnClick="btnDelete_Click"/>

    lblMessage - This is a Lable in your aspx file to display the error message.
    OnClientClick - Executes in Client side.
    9:32 am
    To select all check boxes in Grid View
    Here is the Java Script to select all the Check Boxes in the GridView:

    <script type="text/javascript" language="javascript">
        function SelectAll(id)
        {
            var gdvid = document.getElementById('GridView1');
            var grid = gdvid.ClientID;
            var cell;
            if(gdvid.rows.length > 0)
            {
                for(i=0; i< gdvid.rows.length; i++)
                {
                    cell = gdvid.rows[i].cells[0];
                   
                    for(j=0; j<cell.childNodes.length; j++)
                    {
                        if(cell.childNodes[j].type == "checkbox")
                        {
                            cell.childNodes[j].checked = document.getElementById(id).checked;
                        }
                    }
                }
            }
        }

        </script>

    On Row Data Bound, the following code should be written:

    protected void GridVIew1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    ((CheckBox)e.Row.FindControl("chkSelect")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("chkSelect")).ClientID + "')");
                }
        }
        }
    Friday, September 26th, 2008
    3:57 pm
    Maintain Scroll Position after Asynchronous Postback

    Do you want to maintain the scroll position of a GridView, Div, Panel, or whatever that is inside of an UpdatePanel after an asynchronous postback?  Normally, if the updatepanel posts back, the item will scroll back to the top because it has been reloaded.  What you need to do is “remember” where the item was scrolled to and jump back to there after the postback.  Place the following script after the ScriptManager on your page.  And since the _endRequest event of the PageRequestManager happens before the page is rendered, you’ll never even see your item move!
     

    <script type="text/javascript">
        var xPos, yPos;
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_beginRequest(BeginRequestHandler);
        prm.add_endRequest(EndRequestHandler);
        function BeginRequestHandler(sender, args) {
            xPos = $get('scrollDiv').scrollLeft;
            yPos = $get('scrollDiv').scrollTop;
        }
        function EndRequestHandler(sender, args) {
            $get('scrollDiv').scrollLeft = xPos;
            $get('scrollDiv').scrollTop = yPos;
        }
    </script>

    Thursday, September 25th, 2008
    5:41 pm
    Reseed Identity values in SQL Server
    Here is the query to reseed the identity values in a Table.

    DBCC CHECKIDENT(mytable, reseed, 10)

    mytable - It is the table name you want to reseed.
    10 - Reseed should begin with the number.

    You can also use Truncate command, but truncate will remove all the data and you can begin the Identity value from 1. Whereas in DBCC CHECK IDENT, your data won't be deleted.

    Regards,
    achu



    Current Mood: cheerful
    Tuesday, July 17th, 2007
    11:08 pm
    a good aptitude question
    A B C
           D
           E F G
                   H
                    I
                   
    Numbers between 1 to 9 can be used only once for each letter. The sum of all row and column is 13. For example, A+B+C = 13, C+D+E =13 etc. What will be the digit for E?

    I couldn't find out the answer exactly, but I guess E will have 6. I guess this answer of my own calculation. If anyone can find, please post.

    Cool.........

    achu

    Current Mood: confused
About LiveJournal.com