29 March 2012

get web.config appsettings in javascript

var conn = '<%=ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString %>'
alert(conn);

var v1 = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
var v1 = '<%=ConfigurationManager.AppSettings["var1"] %>'

<%$AppSettings:Title%>

alert(v1);

 

28 March 2012

restrict textbox to allow only numerics

function numerics()
{
 key = String.fromCharCode(window.event.keyCode);
 if (!(key >= '0' && key <= '9'))   window.event.keyCode=0;
}
<asp:TextBox ID="txt1" Text=""  runat="server"  onkeypress=" return numerics();"></asp:TextBox>

function isAlpha(keyCode)
{
    return ((keyCode >= 65 && keyCode <= 90) || keyCode == 8||keyCode==37||keyCode==39||keyCode==9||keyCode==46)
}

function isNum(keyCode)
{
    return((keyCode < 105 && keyCode > 96)||(keyCode < 57 && keyCode > 48) || keyCode == 8||keyCode==37||keyCode==39||keyCode==9||keyCode==46)
}

<asp:TextBox ID="txtUserName" runat="server" onkeydown = "return isAlpha(event.keyCode);" onpaste =  "return false;" Width="130px"></asp:TextBox>

public static bool IsNumeric(String strVal)
    {
        Regex reg = new Regex("[^0-9-]");
        Regex reg2 = new Regex("^-[0-9]+$|^[0-9]+$");
        return (!reg.IsMatch(strVal) && reg2.IsMatch(strVal));
    }

21 March 2012

check all checkboxes in a form

$(document).ready(function() {
            $('#chkAll').click(
             function() {
                 $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
             });
         });

checkbox list javascript validation

function valid()
    {   
       var chkBoxList = document.getElementById('<%=CheckBoxList11.ClientID %>');
        var chkBoxCount= chkBoxList.getElementsByTagName("input");
        var k=0;
        for(var i=0;i<chkBoxCount.length;i++)
        {
            if(chkBoxCount[i].checked)
            k++;
        }
        if(k==0)
        alert("select any item");
        return false;
    }

13 March 2012

Remove duplicates from an interger array

int[] a = { 1, 3, 2, 5, 6, 1, 2, 3 };
string s =",";
for (int i = 0; i < a.Length - 1; i++)
{
if (!s.Contains("," + a[i].ToString() + ","))
{
s += "," + a[i].ToString() + ",";
}
}
string ss = s.Replace(",,",",");
string sss = ss.Substring(1,ss.Length-2).Trim();
string[] aa = ss.Split(',');
int[] n=new int[ss.Split(',').Length-2];
for (int i=1;i<aa.Length-1;i++)
{
        if (aa[i].Replace(",", "")!="")
        n[i-1] = int.Parse(aa[i].Replace(",",""));
}
return n;

07 March 2012

cookie in js

$.cookie('test', $('#Text1').val());

array in javascript

<p id="div_p"></p>


var array = ["S", "V", "B"];
document.getElementById("div_p").innerHTML = array

var arrIDs=new Array();
arrIDs.push(e);
document.getElementById("div_p").innerHTML=arrIDs.join(',');

var arr = new Array(3);
arr[0] = "a";
arr[1] = "b";
arr[2] = "c";

var array1 = new Array("S", "V", "B");

//for object
var person = {firstName:"John", lastName:"Doe", age:46};


At position 2, add the new items, and remove 1 item:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1, "Lemon", "Kiwi");

The result of fruits will be:
Banana,Orange,Lemon,Kiwi,Mango

31 January 2012

timer countdown in asp.net

Label4.Text = "00";
Label5.Text = "02";
Label6.Text = "00";

        if (Label6.Text == "00" || Label6.Text == "0")
        {
            if (Label5.Text == "00" || Label5.Text == "0")
            {
                if (Label4.Text == "00" || Label4.Text == "0")
                {
                    Timer1.Enabled = false;
                }
                else
                {
                    Label4.Text = (Convert.ToInt32(Label4.Text) - 1).ToString();
                    if (Label4.Text.Trim().Length == 1)
                        Label4.Text = "0" + Label4.Text;
                    Label5.Text = "60";
                }
            }
            else
            {
                Label5.Text = (Convert.ToInt32(Label5.Text) - 1).ToString();
                if (Label5.Text.Trim().Length == 1)
                    Label5.Text = "0" + Label5.Text;
                Label6.Text = "60";
            }
        }
        else
        {
            Label6.Text = (Convert.ToInt32(Label6.Text) - 1).ToString();
            if (Label6.Text.Trim().Length == 1)
                Label6.Text = "0" + Label6.Text;
        }

25 January 2012

Tooltip for dropdownlist items

It is common in most web pages that whole text in dropdown lists cannot be seen due to width limitation. One solution for this would be adding tooltip for the dropdown, so that when selecting a value from dropdown, whole text will be appear as a tooltip. For most of browsers implementing tooltip on dropdown control is not a big deal. We can simply add tooltip text with 'title' attribute. C# implementation for this would be as follows

public void SetToolTip(DropDownList ddl)
{
    if (ddl.Items.Count > 0)
    {
        foreach (ListItem item in ddl.Items)
        {
            item.Attributes.Add("Title", item.Text);
        }
    }
}

21 January 2012

change the database name in sqlserver using query

Supported in SQL Server 2000 and 2005
exec sp_renamedb 'databasename' , 'newdatabasename'

Supported in SQL Server 2005 and later version
ALTER DATABASE 'databasename' MODIFY NAME = 'newdatabasename'

select DB_NAME()
select name from sys.databases

07 January 2012

Naming conventions in .net

Pascal case


The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized.


Example:

BackColor, DataSet


Camel case


The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized.


Example:

numberOfDays, isValid


Uppercase


All letters in the identifier are capitalized.


Example:

ID, PI


1).  Private Variables: _strFirstName, _dsetEmployees
2).  Local Variables: strFirstName, dsetEmployees

3).  Namespace:(Pascal) System.Web.UI, System.Windows.Forms

4).  Class Naming:(Pascal) FileStream, Button

5).  Interface Naming:(Pascal) IServiceProvider, IFormatable

6).  Parameter Naming:(Camel) pTypeName, pNumberOfItems

7).  Method Naming:(Pascal) RemoveAll(), GetCharAt()

7).  Method Parameters:(Camel) void SayHello(string name)....
8).  Property / Enumerations Naming:(Pascal) BackColor, NumberOfItems

9).  Event Naming:(Pascal) public delegate void MouseEventHandler(object sender, MouseEventArgs e);

10).  Exception Naming: catch (Exception ex){ }

11).  Constant Naming: AP_WIN, CONST

Some Coding Standards in .net



1.    Use Meaningful, descriptive words to name variables. Do not use abbreviations.







    Good:
    string address
    int salary








     Not Good:

           string name




       string addr

      int sal




2. Do not use single character variable names like i, n, s etc. Use names like index, temp



     variable 'i' is used for for iterations in loops



        Ex:  for ( int i = 0; i < count; i++ ){....}






3.  Do not use underscores (_) for local variable names. But member variables must be prefixed with underscore (_)








4.  Prefix boolean variables, properties and methods with “is” or similar prefixes.




      Ex: private bool _isFinished










5.  File name should match with class name.




       Ex:  for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb) 









6.  Keep private member variables, properties and methods in the top of the file and public members in the bottom.  








7. Use String.Empty instead of “”




      Ex: txtMobile= String.Empty;














8.   8. Avoid having very large files. If a single file has more than 1000 lines of code, it is a good candidate for refactoring. Split them logically into two or more classes.






9. Use StringBuilder class instead of String when you have to manipulate string objects in a loop. The String object works in weird way in .NET. Each time you append a string, it is actually discarding the old string object and recreating a new object, which is a relatively expensive operations.



factorial of number in console applications

int count = 1;
Console.Write("Enter Number for factorial: ");
int number = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= number; i++)
{
count = count * i;
}
Console.Write(count);
Console.Read();

or
public static long numfact(long n)
{
if (n <= 1)
return 1;
else
return n * numfact(n - 1);
}
Console.Write(numfact(5));

palindrome in console applications

string str = string.Empty;
Console.WriteLine("Enter a String");
string s = Console.ReadLine();
int i = s.Length;
for (int j = i - 1; j >= 0; j--)
{
    str = str + s[j];
}
if (str == s)
    Console.WriteLine(s + " is palindrome");
else
    Console.WriteLine(s + " is not a palindrome");

06 January 2012

group by and row no in sql

SELECT ROW_NUMBER()  OVER (ORDER BY  ColumnName1) As SrNo, ColumnName1,  ColumnName2 FROM  TableName

SELECT DENSE_RANK()  OVER (ORDER BY  ColumnName1) As SrNo, ColumnName1,  ColumnName2 FROM  TableName

select top 1 ROW_NUMBER()over(orderby col1)as slno,* from tbl1 orderby slno desc