05 December 2012

Create a table named 'select' with column 'table'

SET QUOTED_IDENTIFIER ON
CREATE TABLE "SELECT" ("TABLE" int)

When SET QUOTED_IDENTIFIER is ON, all strings delimited by double quotation marks are interpreted as object identifiers. Therefore, quoted identifiers do not have to follow the Transact-SQL rules for identifiers. They can be reserved keywords and can include characters not usually allowed in Transact-SQL identifiers

Reference: http://msdn.microsoft.com/en-us/library/aa259228(v=sql.80).aspx

or

CREATE TABLE [SELECT] ([TABLE] INT)

15 November 2012

Customize sql startup query window from:

C:\Users\My-PC\AppData\Local\VirtualStore\Program Files (x86)\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\SsmseeTemplates\Sql\SqlFile.sql

(Chclt)

C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\SqlWorkbenchProjectItems\Sql\SqlFile.sql

06 October 2012

Replace multiple spaces with one/none in sql server

select replace(replace(replace(LTrim(RTrim('      6      Spaces  6      Spaces.      ')),'  ',' |'),'| ',''),
--'|','')
' |','')

select replace(
replace(
replace(
LTrim(RTrim('      6      Spaces  6      Spaces.      '))
,' ',' |')
,'| ',''),
' |',' ')

--Trim the field
--Mark double spaces
--Delete double spaces offset by 1
--Tidy up

sort array of int values without using built-in functions (using Bubble sort)

string res = "";
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
for (int k = 0; k < arr.Length; k++)
{
for (int i = 0; i < arr.Length - 1; i++)
{
if (arr[i] > arr[i + 1])
{
int hold = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = hold;
}
}
res += arr[k].ToString();
arr[k] = arr[k];
}

string s = "1,2,3,,3,2";
string[] ss = (s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
for (int k = 1; k < ss.Length; k++)
{
for (int i = 0; i < (ss.Length - 1); i++)
{
if (Convert.ToInt32(ss[i].Trim()) > Convert.ToInt32(ss[i + 1].Trim()))
{
string hold = ss[i];
ss[i] = ss[i + 1];
ss[i + 1] = hold;
}
}
}
s = string.Join(",", ss);

04 October 2012

split string in c# with regular expression instead of forloop

string s = "er32(s),re4'wr(a),f2.0(t)A(y),(a)";
        s = Regex.Replace(s, @"[\w\s';.&,:]+\(([\w\d.]+)\)", "$1");
        Response.Write(s);

Convert column to row in SQL Server

splitter

select (select convert(varchar(max),id)+',' from #tbl1 for xml path('')) colTOrow

coltorow

11 September 2012

Get the html control to asp without using runat='server' property

string strValue = Page.Request.Form["name of the control"].ToString();

How to get the current row in the grid view rowcommand event

GridViewRow row = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;

In RowDataBound for datakeys

GridView1.DataKeys[e.Row.RowIndex].Value.ToString()

((DataRowView)e.Row.DataItem)["mainid"].ToString()

20 August 2012

persistedselection property for a gridview control in asp

You can specify how row selection is persisted when the GridView control is in paging mode. By default, row selection is persisted by row index. For example, if the second row in a page is selected, the second row in all pages will be selected.

Alternatively, you can specify that row selection is persisted by data-row key. In that case, when a row is selected, rows in other pages are not selected. To enable this functionality, set the EnablePersistedSelection property to true as shown in the following example:

<asp:GridView id="GridView1" runat="server" PersistedSelection="true">
</asp:GridView>

datarow to dataset in asp

DataTable dt = (DataTable)ViewState["tabData"];
DataRow[] dr = dt.Select("test_cd='899'");

DataSet dsnew = new DataSet();
DataTable dtnew = dt.Clone();
dtnew.Constraints.Clear();
DataRow drnew = dtnew.NewRow();

drnew.ItemArray = dr[0].ItemArray;
dtnew.Rows.Add(drnew);
dsnew.Tables.Add(dtnew);

15 August 2012

Query to attaching of database using only .mdf file without associated log file

CREATE DATABASE ... FOR ATTACH_REBUILD_LOG

with log file: CREATE DATABASE ... FOR ATTACH

Order of the sqlquery that logically processed

What is the order of execution in the following list?

  • select

  • from

  • where

  • group by

  • order by

  • having


A: from,where,group by,having,select,order by

ref:  http://msdn.microsoft.com/en-us/library/ms174149.aspx

Rename/Alter the column for a table in sqlserver

To add new column: Alter Table TableName add ColName dataType

To alter a column: Alter Table TableName Alter Column ColumnName DataType NULL/NOT NULL

To rename a column:

EXEC sp_rename
@objname = ' TableName. OldColumnName’,
@newname = 'New ColumnName',
@objtype = 'COLUMN'

note: computed columns(col3=col1+col2) doesnt hav a chance to rename, the only way is it has to be dropped and added back

Ex: Alter Table tblAddress Alter Column Address VARCHAR(512) NULL

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

To rename the table name:

sp_RENAME 'TestTable', 'NewTable'

14 August 2012

can u set innerjoin for update command?

Update Employee set State = s.StateID  
from Employee e  
inner join State s on e.State = s.StateName

Decide whether i/p parameter contains integers or not in sqlserver

IF PATINDEX('%[0-9]%',@val) > 0  
print 'i/p value contain integer'
else
print 'Not contain integer'

13 August 2012

Insert records (multiple) into a table using single query in sqlserver

create table tblEmp (eid int, ename varchar(20), estatus bit)

sqlserver2005

basic: insert into tblEmp values (0,'emp', 'True')

insert into tblEmp select 1,'emp1','True'

union all select 2,'emp2','True'

union all select 3,'emp3','True'

sqlserver2008

insert into tblEmp values (1,'emp1','True'),(2,'emp2','True'),(3,'emp3','True')

If table not exist in database then:

select * into tblEmp from (select 1 eid,'emp1' ename,'True' estatus) tbltemp

22 July 2012

SQL Command Types

DDL is Data Definition Language statements. Some examples:

  • CREATE - to create objects in the database

  • ALTER - alters the structure of the database

  • DROP - delete objects from the database

  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed

  • RENAME - raname column for a table

  • COMMENT - add comments to the data dictionary


DML is Data Manipulation Language statements. Some examples:

  • SELECT - retrieve data from the a database

  • INSERT - insert data into a table

  • UPDATE - updates existing data within a table

  • DELETE - deletes all records from a table, the space for the records remain

  • CALL - call a PL/SQL or Java subprogram

  • EXPLAIN PLAN - explain access path to data

  • LOCK TABLE - control concurrency


TCL is Transaction Control Language statements. Some examples:

  • COMMIT - save work done

  • SAVEPOINT - identify a point in a transaction to which you can later roll back

  • ROLLBACK - restore database to original since the last COMMIT

  • SET TRANSACTION - Change transaction options like what rollback segment to use


DQL/DRL is Data Query/Retrieve Language statements. Some examples:

  • SELECT - retrieve data from the a database


DCL is Data Control Language statements. Some examples:

  • GRANT - gives user's access privileges to database

  • REVOKE - withdraw access privileges given with the GRANT command

  • DENY - remove user's access privileges to database

select distinct of rows from a table of multiple duplicate columns

create table emp(empid int,empname varchar(50),sal money,status bit)

insert into emp select 1,'satya',20000,1 union all
select 1,'satya',20000,2 union all
select 1,'satya',20000,1000 union all
select 2,'sant',21000,-3 union all
select 3,'chclt',42000,0

alter table emp add cno int identity(1,1)

select empid, empname, sal from emp where cno in (select min(cno) from emp group by empid,empname,sal,comm,status)

output

empid empname sal
1           satya          20000
2           sant            21000
3           chclt           42000

alter table emp drop column cno

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

with x as(select *,row_number() over(partition by empid,empname,sal,comm,status order by empid) as count from emp)
delete from x where count>1

16 July 2012

array conversions

using System;
using System.Collections.Generic;
---------------------------
arraylist to array
> string[] a = (string[])arraylist.toarray(typeof(string));
> arraylist.copyto(array,0);
list to array
> string[] a = list.toarray();
---------------------------
arraylist to arraylist
> arraylist.addrange(arraylist);
---------------------------
array to arraylist
> arraylist.addrange(array);
> arraylist a = new arraylist(array);
array to list
> list<string> l = new list<string>(array)
> list<string> l = array.tolist();
---------------------------
array to array
> string[]  a = (string[])array.clone();// Clone method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array
---------------------------
array declaration and intilization methods
int[] a;
a = new int[3]{3,5,6};
int[] a = new int[]{3,4,5};
int[] a = new int[3]{3.4,5};
int[] a = new int[3];
a[0] = 2; a[1] = 3; a[2] = 4;
---------------------------
search arraylist
arraylist.sort();
arraylist.binaryseach(43);
arraylist.indexof(searchstr , 0);
---------------------------
string to bytearray
> byte[] = (new UnicodeEncoding()).GetBytes(stringToConvert);
---------------------------
bytearray to string
>char[] cs = new char[bs.Length];
for (int i = 0; i < cs.Length; ++i)
{
cs[i] = Convert.ToChar(bs[i]);
}
---------------------------

char array to string
string str = new string(chararray);

string to char array
string s = "hello";
char[] c = s.ToCharArray();
---------------------------

array to datatable

>DataTable dataTable = new DataTable();dataTable.LoadDataRow(array, true);//Pass array object to LoadDataRow methodreturn dataTable;
---------------------------
get array size
array.getlength(0).tostring();
array.getlowerbound(0).tostring();
---------------------------
better to use List instead of ArrayList
better to use Dictionary instead of HashTable

15 July 2012

General Page Life-Cycle Event Stages

The events occur in the following sequence.

Its best to turn on tracing(<% @Page Trace=”true”%>) and track the flow of events :

PageRequest – The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled(therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start – In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

PreInit– This event represents the entry point of the page life cycle. If you need to change the Master page or theme programmatically, then this would be the event to do so. Dynamic controls are created in this event.
protected void Page_PreInit(object sender, EventArgs e)

Init – Each control in the control collection is initialized. i.e., During page Intialization, controls on the page are available and each control’s UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from viewstate.
protected void Page_Init(object sender, EventArgs e)

Init Complete* - Page is initialized and the process is completed.
protected void Page_InitComplete(object sender, EventArgs e)

PreLoad* - This event is called before the loading of the page is completed.
protected void Page_PreLoad(object sender, EventArgs e)

Load– This event is raised for the Page and then all child controls. The controls properties and view state and control state can be accessed at this stage. This event indicates that the controls have been fully loaded.
protected void Page_Load(object sender, EventArgs e)

LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also marks the beginning of the rendering stage.
protected void Page_LoadComplete(object sender, EventArgs e)

PreRender – If you need to make any final updates to the contents of the controls or the page, then use this event. It first fires for the page and then for all the controls.
protected void Page_PreRender(object sender, EventArgs e)

Savestate

Rendering – Before rendering, viewstate is saved for the page and all controls. At this stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page’s Response property.

PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.
protected void Page_PreRenderComplete(object sender, EventArgs e)

SaveStateComplete* - In this event, the current state of the control is completely saved to the ViewState.
protected void Page_SaveStateComplete(object sender, EventArgs e)

Unload – This event is typically used for closing files and database connections. At times, it is also used for logging some wrap-up tasks.
protected void Page_Unload(object sender, EventArgs e)

 

The events marked with *  have been introduced in ASP.NET 2.0.

Untitled

page life cycle -- click to download the document

 

Comparison with Init and Load events in Master and content pages:











Page Init EventPage Load event
1. Execution sequence starts from Init event of Main master page--> Sub Master Page --> ……. -->Requested ASPX page init event.1. Execution sequence starts from Load event of Requested ASPX page --> Sub Master Page --> ……. --> Main master page load event.

 

09 July 2012

convertion differences between Convert.ToInt32 and int.Parse

int.Parse("12") --> 12
int.Parse("12.12") --> Format Ex
int.Parse(null) --> Null Ex
int.Parse("889708888888899888888098980909089808990890890890900") --> overflow Ex

convert.ToInt32("12") --> 12
convert.ToInt32("12.12") --> Format Ex
convert.ToInt32(null) --> 0
convert.ToInt32("889708888888899888888098980909089808990890890890900") --> overflow Ex

int re = convert.ToInt32(Session["val"]); --> 0
int re = int.Parse(Session["val"]); --> ArgumentNULLException

int re = 0, res;
if (int.TryParse(re.ToString(), out res))
{ string fds = res.ToString(); }
else
{ string dfsa = res.ToString(); }

re = Convert.ToInt32(ViewState["fdsa"]); --> 0
re = (int)ViewState["fdsa"]; --> null reference exception, Object reference not set to instance of an object // it is fastest than all
re = int.Parse(ViewState["fdsaf"].ToString()); --> null reference exception, Object reference not set to instance of an object
--
Convert.ToString() handles the NULL
.ToString() throws the NULL reference exception

28 June 2012

clear all cotrol values of a page

<script type="text/javascript">
    function allclear()
    {    //debugger
        var elements=document.getElementsByTagName("INPUT");
        for(i=0;i<elements.length;i++)
            if(elements[i].type=="radio")
                elements[i].checked=false;
        for(i=0;i<elements.length;i++)
            if(elements[i].type=="checkbox")
                elements[i].checked=false;
        for(i=0;i<elements.length;i++)
           if (elements[i].type=="text")
                elements[i].value="";
        var elements1=document.getElementsByTagName("SELECT");
        for(i=0;i<elements1.length;i++)
            if(elements1[i].id!="" && elements1[i].id!=null)
                elements1[i].selectedIndex=0;
     }
</script>
---------------------------------------------------------------------------------------
private void ClearControls(Control c)
    {
        if (c.GetType() == typeof(System.Web.UI.WebControls.TextBox))
            ((TextBox)c).Text = "";
        if (c.GetType() == typeof(System.Web.UI.WebControls.RadioButtonList))
        {
            RadioButtonList rbtl = (RadioButtonList)c;
            for (int j = 0; j < rbtl.Items.Count; j++)
                rbtl.Items[j].Selected = false;
        }
        if (c.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
            ((DropDownList)c).SelectedIndex = 0;
        if (c.GetType() == typeof(System.Web.UI.WebControls.RadioButton))
            ((RadioButton)c).Checked = false;
        foreach (Control child in c.Controls)
            ClearControls(child);
}

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

  private void DisableControls(Control c)
    {
        if ((c is TextBox) || (c is LinkButton) || (c is Button) || (c is CheckBox) || (c is CheckBoxList) || (c is RadioButtonList) || (c is DropDownList) || (c is Panel) || (c is ImageButton))
        {
            ((WebControl)c).Enabled = false;
        }
        foreach (Control child in c.Controls)
            DisableControls(child);
    }

make listbox items colorful

protected void Page_PreRender(object sender, EventArgs e)
{
    bool flag=false;
    foreach (ListItem li in ListBox1.Items)
    {
        if (flag)
        {
            li.Attributes.Add("class", "optred");
            flag = false;
        }
        else
        {
            li.Attributes.Add("class", "optblue");
            flag = true;
        }
    }
}
<style type="text/css">
.optred{background-color:red;}
.optblue{background-color:blue;} 
</style>

make webpage title scrolling

<script type="text/javascript">
    msg = "MyWebPageTitle";
    msg = "..." + msg;pos = 0;
    function scrollMSG() {
    document.title = msg.substring(pos, msg.length) + msg.substring(0, pos);
    pos++;
    if (pos >  msg.length) pos = 0
    window.setTimeout("scrollMSG()",200);
    }
    scrollMSG();
</script>

javascript handlers

// Add handler using the getElementById method
$addHandler(Sys.UI.DomElement.getElementById("Button1"), "click", toggleCssClassMethod);
// Add handler using the shortcut to the getElementById method
$addHandler($get("Button2"), "click", removeCssClassMethod);

String formats

String strVal = "a(1), a1(2), a.3(3), a'4 (4), a.5:(5)";
Regex.Replace(strVal, @"[\w\s';.&,:]+\((\d+)\)", "$1") = 1,2,3,4,5
-----------------------------------------------------------------------
string dNum = "32.123456";
string.Format("{0:c}", double.Parse(dNum)) = $32.12
string.Format("{0:n}", double.Parse(dNum)) = 32.12
string.Format("{0:D}", DateTime.Now) = Thursday, June 28, 2012
string.Format("{0:T}", DateTime.Now) = 10:59:28 AM
DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") = 28/06/2012 10:59:28
---------------------------------------------------------------------------------
decimal dNum = decimal.Parse("32.12345");
Response.Write(dNum.ToString("0.00"));

01 June 2012

image file path to byte[] format

private byte[] imgStream(string filePath)
{
MemoryStream stream = new MemoryStream();
tryagain:
try
{ Bitmap bmp = new Bitmap(filePath);
  bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex) { goto tryagain; }
return stream.ToArray();
}

System.Drawing.ColorTranslator.FromHtml("#D8BFD8");

25 May 2012

Get RowCount all tables of a Database in SqlServer

SELECT [TableName] = O.name, [RowCount] =MAX(I.rows)FROM sysobjects O, sysindexes I
WHERE O.xtype ='U'AND I.id =OBJECT_ID(O.name)
GROUP BY O.name ORDER BY [RowCount] DESC

Email validation javascript

function emailCheck(str)
{
var at="@";
var dot=".";
var lat=str.indexOf(at);
var lstr=str.length;
var ldot=str.indexOf(dot);
if (str.indexOf(at)==-1)
    return false;
if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
    return false;
if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
    return false;
if (str.indexOf(at,(lat+1))!=-1)
    return false;
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
    return false;
if (str.indexOf(dot,(lat+2))==-1)
   return false;
if (str.indexOf(" ")!=-1)
   return false;
return true;
}

18 April 2012

Get current date n time in sqlserver

select current_timestamp
go
select {fn now()}
go
select getdate()
go
select convert(varchar,getdate(),101)*
go
sqlserver2005 -- select convert(varchar(8),getdate(),108), convert(varchar(8),getdate(),101) 
sqlserver2008 -- select convert(time,getdate()), convert(date,getdate(),101)

 *Each style will give the output of the date in a different format.
The default style it uses is 100.
The style values can be ranging between 100-114, 120, 121, 126, 127, 130 and 131 or 0 to 8, 10, 11, 12 and 14 in this case century part will not returned.

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

sql syntaxes

Select Statement
SELECT "column_name" FROM "table_name"

Distinct
SELECT DISTINCT "column_name" FROM "table_name"

Where
SELECT "column_name" FROM "table_name" WHERE "condition"

And/Or
SELECT "column_name" FROM "table_name" WHERE "simple condition" {[AND|OR] "simple condition"}+

In
SELECT "column_name" FROM "table_name" WHERE "column_name" IN ('value1', 'value2', ...)

Between
SELECT "column_name" FROM "table_name" WHERE "column_name" BETWEEN 'value1' AND 'value2'

Like
SELECT "column_name" FROM "table_name" WHERE "column_name" LIKE {PATTERN}

Order By
SELECT "column_name" FROM "table_name" [WHERE "condition"] ORDER BY "column_name" [ASC,DESC]

Count
SELECT COUNT("column_name") FROM "table_name"

Group By
SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1"

Having
SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1" HAVING (arithematic function condition)

Create Table Statement
CREATE TABLE "table_name" ("column 1" "data_type_column_1", "column 2" "data_type_for_column_2",.... )

Drop Table Statement
DROP TABLE "table_name"

Truncate Table Statement
TRUNCATE TABLE "table_name"

Insert Into Statement
INSERT INTO "table_name" ("column1", "column2", ...) VALUES ("value1", "value2", ...)

Update Statement
UPDATE "table_name" SET "column_1" = [new value] WHERE {condition}

Delete From Statement
DELETE FROM "table_name" WHERE {condition}

select--scalar--string, update,insert,delete--nonquery--int

Ref: 

http://www.1keydata.com/sql/sql-syntax.html

http://www.sqlcommands.net/

02 January 2012

C# Features not in Java

•No automatic fall-through from one case block to the next

•Strongly-typed enums

•By reference calls are explicit at caller AND callee

•Method overrides are explicit

•Supports versioning

•Structs (value types)

•Integrated support for properties and events

•Can still use pointers with RAD language

Can share data and use functionality with components written in many different languages

Development tools and Documentation
—Server-side is well supported by both Java and .NET IDEs

—On the client-side .NET IDEs benefit from the fact that .NET CF is so close to .NET  (With Java there are separate IDEs for desktop and mobile application development)

—Compatibility problems between Java vendors

—Java IDEs are slow!

—C# is a richer/more complex language than Java

—Both Java and .NET have well documented API

—Web service documentation

—.NET - MSDN

—Java – Google

—Support for encryption of web services

—.Net CF: HTTPS and SOAP extensions

J2ME: HTTPS, but only in CDC & MIDP 2.0

C# and JAVA


CSharp and JAVA are two different Object Oriented Languages , both have some similarities and differences also . The Csharp and JAVA derived from their own single ancestor Class "Object". All Classes in C# are descended from System.Object Class and in JAVA all classes are subclasses of java.lang.Object Class.

Both C# and JAVA have their own runtime environments . C# source codes are compiled to Microsoft Intermediate Language (MSIL) and during the execution time runs it with the help of runtime environments - Common Language Runtime (CLR). Like that JAVA source codes are compiled to Java Byte Code and during the execution time runs it with the help of runtime environments - Java Virtual Machine (JVM). Both CSharp and JAVA supports native compilation via Just In Time compilers.

More over both C# and JAVA have their own Garbage Collector. In the case of keywords comparison some keywords are similar as well as some keywords are different also. The following are the examples of few similar and different keywords.

Similar Keywords examples

class , new , if , case , for , do , while , continue , int , char , double , null

 

joins example

table1                                  table2

col1 col2                         col3   col4

 1      a                              1       a

 2      b                              2       b

null    c                              3       c

 4     null                           null     d

inner join result:

col1 col2 col3 col4

 1      a     1      a

 2      b     2      b

left outer join result:

col1 col2 col3 col4

  1      a     1     a

  2      b      2    b

 null    c    null  null

  4     null  null  null

full outer join result: 

col1 col2 col3 col4

  1      a     1     a

  2      b      2    b

  null    c    null  null

   4     null  null  null

 null    null    3    c

 null    null   null  d