25 December 2013

how to find number of weeks between two dates

SELECT DATEDIFF(wk,'2012-01-01', '2012-01-31')

When you want to replace a possibly null column with something else, use IsNull.


When you want to replace a possibly null column with something else, use IsNull.


SELECT ISNULL(myColumn, 0 ) FROM myTable

Naming Convention in asp.net

btn  -  Button
              cb   -  CheckBox
              cbl  -  CheckBoxList
              ddl  -  DropDownList
              dtv  -  DetailsView
              fmv  -  FormView
              grdv -  GridView
              hl   -  Hyperlink
              img  -  Image
              ib   -  ImageButton
              lbl  -  Label
              lbtn -  LinkButton
              lb   -  ListBox
              lit  -  Literal
              mnu  -  Menu
              pnl  -  Panel
              ph   -  PlaceHolder
              rb   -  RadioButton
              rbl  -  RadioButtonList
              rpt  -  Repeater
              sql  -  SqlDataSource

              txt  -  Textbox

Replace command in sqlserver

declare @input varchar(200)
  set @input='jc.adi narayana reddy'
 
  select REPLACE(@input,'a','b')


output

jc.bdi nbrbybnb reddy

Replace command in c#.

 mystring = srcstring.Replace("old", "New");

Creating of Random numbers within the given range.

 Random randobj = new Random();
test1.Text = randobj.Next(0, 359).ToString();
 test2.Text = randobj.Next(60, 110).ToString();

C# Program to Copy a File into Another File

This program will help C# developers to copy a gen file into another file using C# inbuilt function. There is a direct method to copy file File.Copy,  where you need to pass source and target files path.
Another method is get the fileinfo and the then call CopyTo method of fileinfo object. The code for both the methods are given below. Please comment if you face any problem.
using System;
using System.IO;
namespace MyApp
{
    class file_copy_class
    {
        public static void Main(string[] args)
            {
            string source_file = @"d:\source\test.txt";
            string target_file = @"d:\target\test.bak";
            //Method 1
            if (File.Exists(source_file))
            {
                File.Copy(source_file, target_file, true);
            }
            //Method 2
            if (File.Exists(source_file))
            {
                FileInfo objFile = new FileInfo(source_file);
                objFile.CopyTo(target_file, true);               
 
            }


                     Console.Read();
        }
    }
}

How to access datasource(label,textbox,etx.) fields in an ASP.NET Repeaters ItemCommand event?

protected void rpt_rooms_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "book")
                {
                    DropDownList ddl_age_ = e.Item.FindControl("ddl_age") as DropDownList;
                    string abc = ddl_age_.SelectedValue;
                }
            }
            catch (Exception ex)
            {
                lblerror.Visible = true;
                lblerror.ForeColor = System.Drawing.Color.Red;
                lblerror.Text = ex.Message;
            }

        }

How to access datasource(label,textbox,etx.) fields in an ASP.NET Repeaters ItemDataBound event?

// This event is raised for the header, the footer, separators, and items.
        protected void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {
            // Execute the following logic for Items and Alternating Items.
            if (e.Item.ItemType == ListItemType.Item ||
                e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (((Evaluation)e.Item.DataItem).Rating == "Good")
                {
                    ((Label)e.Item.FindControl("RatingLabel")).Text = "<b>***Good***</b>";
                }
            }
        }

(or)

        protected void rptMyReteater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Button b = e.Item.FindControl("myButton") as Button;
                DataRowView drv = e.Item.DataItem as DataRowView;
                b.CommandArgument = drv.Row["ID_COLUMN_NAME"].ToString();
            }
        }


(OR)

protected void rpt_rooms_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    Label roomid = (Label)e.Item.FindControl("Label1");
                    Label room_type_id = (Label)e.Item.FindControl("Label2");
                    GridView gvreply = e.Item.FindControl("gvreply") as GridView;
                    gvreply.DataSource = dt;
                    gvreply.DataBind();

                    DataList dl_gallery = e.Item.FindControl("dl_gallery") as DataList;
                    dl_gallery.DataSource = dt3;
                    dl_gallery.DataBind();

                     DropDownList ddl_extra_beds = e.Item.FindControl("ddl_extra_bed") as DropDownList;
                }
            }
            catch (Exception ex)
            {
                lblerror.Visible = true;
                lblerror.ForeColor = System.Drawing.Color.Red;
                lblerror.Text = ex.Message;
            }

        }





Currency Format with comma's in SQL Server

Sometimes you want to have your money fields properly formatted with commas like this: 10,000,000.34


DECLARE @amount AS DECIMAL
SET @amount=11000000
SELECT CONVERT(VARCHAR,CAST(@amount AS MONEY),-1) AS 'Amount'

Output



How to Reset the identity column in sql server

Because Identity on a column by default is Off. We can reset it as 

SET IDENTITY_INSERT 'TABLENAME' ON

And again off this as

SET IDENTITY_INSERT 'TABLENAME' OFF 

How and when to use LIKE statement ?

Like will be use when search records i.e start with, end with, contains a particuar character in string as

1. start with 's'
select * from emp where empName like 's%'
2. end with 's'
select * from emp where empName like '%s'
1. contain 's'
select * from emp where empName like '%s%' 

When, Where and Why XML used

There are lots of places we can use XML

1. Where we need a place to hold some data, can read / write / manipulate without having any database. Even we can use textfile, but XML is more flexible – say which field, what is the data type, etc., if we use text file, we need to predefine what is the sequence of each column and what dataype etc.,
2. Where we need to transfer some data from one pace to another like one layer to another, one tier to another etc., – we can serialize the xml and deserialize it in destination place.
3. Where we need a light weight file, and flexible to handle almost like a database …
4. XML is not languages specific, can read in any program language like .NET, Java, VB, Javascript etc., 

what is difference between Write() and WriteLine() methods in .Net

Write() Method will keep the cursor on the same Line after writing the data.

WriteLine() Method will take cursor to new Line.

Validate FileUpload Control to Allow maximum 15MB to Upload

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="fileupload_size.aspx.cs"
    Inherits="fileupload_size" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src=" http://code.jquery.com/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#btn_upload').click(function () {

                var f = $('#fileupload1')[0].files[0];
                var size = (f.size / 1024 / 1024).toFixed(2); //convert size byte to mb
                if (f.size > 15728640) {
                    alert("Your File Size is " + size + "MB, Maximum Allow is 15MB");
                    return false;
                }
                else {
                    return true;
                }

            })
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <center>
    <br />
    <br />
    <div>
        <table>
            <tr>
                <td>
                    Upload file
                </td>
                <td>
                    <asp:FileUpload ID="fileupload1" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <asp:Button ID="btn_upload" runat="server" Text="Upload" />
                </td>
            </tr>
        </table>
    </div>
    </center>
    </form>
</body>

</html>

Static class in C#

C# provides the important feature to create static classes, there are two main features of a static class, one is no object of static class can be created and another is, a static class must contain only static members, then it is important that what is the main benefit to create a static class, the main benefit of making static class, we do not need to make any instance of this class ,all members can be accessible with its own name.
Declaration:
A static class is created by using keyword 'Static' as shown here:
Static class Clasname
{
  
 //C#
}
One more thing that is notable-within static class, all members must be explicitly specified as static, static class does not automatically make its members static. Static class can contain a collection of static methods.
Example:


using System;

        static class Shape
        {
            public static double GetArea(double Width, double height)
            {
                return Width * Height;
            }
        }

        class Ractangle
        {
            private void GetRactangleArea()
            {
                Double Area;
                Area = Shape.GetArea(10, 5);
            }
        }
Shape is static class, it contain staic function GetArea.Ractangle is other class and with in GetArea function can be access without creating instace of Class Shape.

Although a static class cannot have an instance constructor, it can have a static constructor.

Partial Classes in C#

Introduction
A Partial class is one that can be split among multiple physical files. This feature was introduced with the release of C# version 2.0. With C#, we can split the source code for a class into separate files so that we can organize the definition of a large class into smaller, easier to manage pieces. When we split a class across multiple files, we define the parts of the class by using the partial keyword in each file. Each file contains a section of the class definition, and all parts are combined when the application is compiled. Look at the example below:

Original and Single Class File (Calculation.cs)

class ClassRoom
{
        private int boycount;   //field
        public ClassRoom()     //default constructor
        {
            boycount = 30;
        }
        public ClassRoom(int bcount)     //overloaded constructor
        {
            boycount = bcount;
        }
        public double Avg()     //method
        {
            //statements goes here
        }
}

Splitted Class Files into two parts

//Calculation1.cs
partial class ClassRoom
{
    private int boycount;   //field

    public ClassRoom()     //default constructor
    {
        boycount = 30;
    }
}
//Calculation2.cs
partial class ClassRoom
{
    public ClassRoom(int bcount)     //overloaded constructor
    {
        boycount = bcount;
    }
    public double Avg()     //method
    {
        //statements goes here
    }
}

Now, when we compile a class that has been split into separate files, we must provide all the files to the compiler.
Partial Classes Rules and Advantages
To work on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
When working with automatically generated source, code can be added to the class without having to recreate the source file.
To split a class definition, use the partial keyword modifier.
All the parts must have the same accessibility, such as public, private, and so on.

The partial modifier can only appear immediately before the keywords class, struct, or interface.

How to validate 10 digit mobile number in asp.net with regular expression control.

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <div>
        <table>
            <tr>
                <td>
                    <asp:Label ID="Label4" runat="server" Text="Mobile No:" Font-Bold="true"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txt_mobile" CssClass="textform" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ForeColor="Red"
                        ControlToValidate="txt_mobile" Font-Size="X-Small" ErrorMessage="Please enter mobile number"
                        ValidationGroup="valid"></asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="rfvMobil1" Font-Size="XX-Small" ForeColor="Red" ControlToValidate="txt_mobile"
                        ValidationExpression="^[7-9][0-9](\s){0,1}(\-){0,1}(\s){0,1}[0-9]{1}[0-9]{7}$"
                        runat="server" ErrorMessage="Please enter Valid MobileNo" ValidationGroup="valid"
                        Display="Dynamic"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td class="barhds">
                </td>
                <td align="left">
                    <asp:Button ID="btnsubmit" runat="server" Text="Submit" ValidationGroup="valid" />
                </td>
            </tr>
        </table>
    </div>
</asp:Content>