Wednesday, June 29, 2011

How to get constraint of a table

How to get constraint of a table


You can get the constraints of a table from the database.

SELECT t.name AS table_name,o.name
AS
KeyName FROM
sys.Tables
t INNER JOIN
sys.objects
o ON t.OBJECT_ID
= o.parent_object_ID

Using above query you can get all the constraint of a particular table.

How to get column properties from a table

How to get column properties from a table


You can get the columns detail of a table from the database.

SELECT t.name AS table_name,c.name AS column_name,c.is_identity,c.is_nullable,c.max_length,ty.name
AS TypeName FROM sys.Tables
t INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID INNER JOIN sys.types ty ON c.user_type_id=ty.user_type_id

Using above query you can get table columns and columns properties like Column Name,
Data Type, Is Identity, Is Nullable, and Max Length.

How to get entire table name from database

How to get entire table name from database


You can get the entire table name from the database.

SELECT name AS table_name FROM sys.Tables

Using above query you can find entire table name. Suppose In Database there are
three tables like Table A, Table B, Table C. then result will be:

Table A
Table B
Table C

Tuesday, June 28, 2011

Unique Temple in Pehowa

Unique Temple in Pehowa

Pehowa is 26 Km away from Kurukshetra. The town of Pehowa was named after the famous
King "Prithu". Many "Hindus" go to the holy land of Pehowa to worship their dead
ancestors and offer "Pind Daan" in order to release the soul from the cycle of birth
and re- birth.

The town of "Pehowa" is blessed with a famous and unique temple of Lord Kartikkya.
This is one of the unique temples in the world. Women are not allowed
to enter this temple.

When Lord Shiva and Mata Parvati told both children to perform “Trilok parikarma” then
Kartikkya immediately set off on his vehicle, the peacock while Ganesha with his
vehicle Mooshika (mouse) went around the parents and said that our parents are the
whole world to us. So by going around them once, I have gone around the world.

When Kartikkya reached back and saw that Ganesha already won, then he had doubt
that his mother helped Ganesha. So he removed all his skin and gave it to
Mata Parvati and said that skin comes from mother while bones come from father.
After giving up his skin he came to Pehowa temple and said that no women can enter in
this temple - if any woman does, she will die.
.






Monday, June 27, 2011

Difference between Project and Web Site

Difference between Asp.Net Web Application(Project) and Asp.Net Web Site(Website)

  • In Asp.Net Web Application at run time you cannot add/change code. While you can
    do in Asp.Net Web Site.
  • In Asp.Net Web Application you cannot publish single dll of each page while in Asp.Net
    Web Site you can publish dll of each page. This is helpful when there is any change
    in one page then you have to upload dll of that page instead of complete application
    dll.
  • In Asp.Net Web Site each file that you exclude is renamed with an exclude keyword
    in the filename. In the Asp.Net Web Application the project just keeps track of
    which files to include/exclude from the project view without renaming them, making
    things much tide.

Saturday, June 18, 2011

Watermark for username and password using Javascript

Watermark for username and password using Javascript

Javascript for creating watermark. You can use this script for creating watermark effect in username and password.
There are many ways of creating watermark effect using AjaxToolKit, Javascript etc.
But when there is a choice between Javascript and other technology, I will always prefer Javascript.
When you create watermark effect using Ajax Toolkit then password field shows "*" and not text e.g "Password"
This is because you cannot write text in unencrypted form when textmode is password. But you can do this thing using Javascript.

<!--Put this code in Head Section -->
<script language='Javascript' type='text/Javascript'>
//<![CDATA[
function changeUsername() {
document.getElementById('divUsername').style.display = '';
document.getElementById('divDummyUsername').style.display = 'none';
document.getElementById('<% =txtEmail.ClientID %>').focus();
}
function changePassword() {
document.getElementById('divPassword').style.display = '';
document.getElementById('divDummyPassword').style.display = 'none';
document.getElementById('<% =txtPassword.ClientID %>').focus();
}
function restoreUsername() {
if (document.getElementById('<% =txtEmail.ClientID %>').value == '') {
document.getElementById('divUsername').style.display = 'none';
document.getElementById('divDummyUsername').style.display = '';
}
}
function restorePassword() {
if (document.getElementById('<% =txtPassword.ClientID %>').value == '') {
document.getElementById('divPassword').style.display = 'none';
document.getElementById('divDummyPassword').style.display = '';
}
}
//]]>
</script>

<!--Put this code between body Section -->
<div id="divUsername">
<asp:TextBox MaxLength='50' Width='100px' onblur="restoreUsername()" ID='txtEmail' runat='server'>
</asp:TextBox>
</div>
<div id="divDummyUsername">
<asp:TextBox MaxLength='50' Width='100px' onfocus="changeUsername()" Text="Username" ID='txtDummyEmail' runat='server'>
</asp:TextBox>
</div>
<div id="divPassword">
<asp:TextBox MaxLength='50' Width='100px' TextMode="Password" TabIndex="2" ID='txtPassword' runat='server' onblur="restorePassword()"></asp:TextBox>
</div>
<div id="divDummyPassword">
<asp:TextBox MaxLength='50' Width='100px' TabIndex="2" ID='txtDummyPassword' runat='server' Text="Password" onfocus="changePassword()"></asp:TextBox>
</div>
<div>
<input id="HDPassword" runat="server" type="hidden" />
</div>

<!--Put this code at the bottom of page before body tag -->
<script language="Javascript" type="text/Javascript">
if (document.getElementById('<% =HDPassword.ClientID %>').value != '' && document.getElementById('<% =txtPassword.ClientID %>').value == '') {
document.getElementById('<% =txtPassword.ClientID %>').value = document.getElementById('<% =HDPassword.ClientID %>').value;
document.getElementById('divPassword').style.display = '';
document.getElementById('divDummyPassword').style.display = 'none';
}
else {
document.getElementById('divPassword').style.display = 'none';
document.getElementById('divDummyPassword').style.display = '';
}
if (document.getElementById('<% =txtEmail.ClientID %>').value == '') {
document.getElementById('divUsername').style.display = 'none';
document.getElementById('divDummyUsername').style.display = '';
}
else {
document.getElementById('divUsername').style.display = '';
document.getElementById('divDummyUsername').style.display = 'none';
}
</script>

How to retain password during postback

How to retain password during postback in ASP.NET

Generally password is lost when page is post. To save the password during postback you have to save the password in “Value” Attributes of textbox. because Text is the server side properties when page post then password text is lost while "Value" is the HTML properties and does not go to the server side. Hence does not empty during postback.


C#
if (IsPostBack)
{
    if (txtPassword.Text.Trim() != "")
    {
        txtPassword.Attributes["value"]= txtPassword.Text;
    }
}

VB
If IsPostBack Then
      If txtPassword.Text.Trim() <> "" Then
          txtPassword.Attributes("value") = txtPassword.Text
      End If
 End If

Wednesday, June 15, 2011

How to Concatenate string in VBA

How to Concatenate string in VBA

In excel if you have two columns “A” and “B” and you want to concatenate these two columns into single columns suppose “C” then you can use this code for concatenation of two columns. Make its macro and use this code
Sub ConcatenateString()

        Sheets("Sheet1").Select
        Range("C1").Select

        Do Until Selection.Offset(0, -2).Value = ""
                Selection.Value = Selection.Offset(0, -2).Value & " " & Selection.Offset(0, -1)
                Selection.Offset(1, 0).Select
        Loop

        Range("A1").Select

End Sub

How to Split string in VBA

How to Split string in VBA

You can split a string into two substrings. Suppose you have a string in “A” columns then by using the below code you can convert into two substrings in columns “B” and columns “C”. String splits where it finds space.

Sub SplitText()
    Sheets("Sheet1").Select
    Range("C1").Select
    Do Until Selection.Value = ""
          Dim avarSplit As Variant
          avarSplit = Split(Selection.Value, " ")
          Selection.Offset(0, 1).Value = avarSplit(0)
          Selection.Offset(0, 2).Value = avarSplit(1)
          Selection.Offset(1, 0).Select
    Loop
    Range("A1").Select
End Sub

Monday, June 13, 2011

Differences between Datagrid, Datalist and Repeater?

Differences between Datagrid, Datalist and Repeater


  • Datagrid has paging while Datalist and Repeater don’t. Datalist and Repeater have
    a property called repeat. Direction = vertical/horizontal. (This is of great help
    in designing layouts). This is not there in Datagrid.
  • A repeater is used when more intimate control over html generation is required.
  • A repeater has the best performance as its lighter. DataLists and DataGrids have
    inbuilt methods which makes them heavier in load, but also very effective if you
    need to display data in a number of ways (i.e. sorting, indexing, records per page
    etc.) whereas with a Repeater you'd have to implement these yourself.
  • If you simply want to output some data on a page I'd recommend a Repeater. If however
    you'll be manipulating this data in any way, such as sorting etc. Then use a DataList
    or DataGrid. The choice should depend upon the data you have and what you want to
    do with it.
Also as mentioned above it's much easier to implement custom html into a Repeater.
You can still however do this with a DataGrid or DataList. it's just a little trickier.

Sunday, June 12, 2011

Difference Between Asp.Net 2003 and Asp.Net 2005

Difference Between Asp.Net 2003 and Asp.Net 2005


ASP.NET 2003

ASP.NET 2005

When you compile the application in .NET 1.x, Visual Studio 2003 would automatically
compile only certain file types such as ASP.NET pages, Web services, user controls,
HTTP handlers, Resource files, and Global.asax class files. The rest of the files
needed to be explicitly compiled before finally publishing your code to the web
server.

In Visual Studio 2005, you no longer need to compile all the files into an assembly.
The ASP.NET dynamic compilation engine allows to automatically compile applications,
that includes .aspx, .cs, .vb files. That means, simply create an application and
publish it. All the files in the App_Code folder are dynamically compiled to a single
assembly, named code.dll. The assembly has an application scope and is created in
the Temporary ASP.NET Files folder, well outside the Web application space.

There is no option to create dll of single page so if you modify a single code behined
page still you have to upload entire project dll

Giving option to make dll of single page so that if you modify a code behind page
then you can only upload/change that page dll.

The code-behind model requires an IIS virtual directory.

The code-behind model can directly access the local installation of IIS.

The code-behind model lacks support for FTP, local file systems, and direct IIS
access.

The code-behind model has multiple ways to open Web sites.

It requires IIS on the development computer.

It already has a built-in Web server.

Unable to open individual pages outside the project.

Need not open the entire project; you can open individual pages outside the project,
it is achieved through the compile-on-demand feature.

It requires explicit addition of files to the project.

It eliminates the need to explicitly add files to the project.

In ASP.NET 1.x presentation page (aspx) and the code behind page are linked by inheritance
aspx page inherit from the code behind page. But if you want to access any aspx
control then it must be declare in code behind page(when you drag any control then
it automatically generate code into the code behind page but some time it does not
create code when you write html rather then drag the control for that you have to
open design view so that it generate code into the code behind page)

n asp.net 2.0 the presentation page (aspx) and the code behind page are interact
with inheritance same as that of asp.net 1.0 but with additional feature which is
partial class. Partial classes enable you to declare a class in more than one physical
file. When the class gets compiled, one class is generated from all the partial
classes. The advantage of using partial classes is that you don’t need to worry
about declaring a control in both the presentation page and code-behind file. Anything
that you declare in the presentation page is available automatically in the code-behind
file, and anything you declare in the code-behind file is available automatically
in the presentation page.

Wednesday, June 8, 2011

convention followed in making website

convention followed in making website

HTML (Design) Related
1) Fix max length of each control
2) Always define styles in style sheets. In worst case, define style at top of page.
3) Try to categorize the style sheets like general sections and page wise sections.
4) Check page layout and design in IE and Firefox.
5) Check and warn for important cookies or Javascript or Popup if blocked.
6) Put meaningful Page titles for each screen in hierarchy.
7) Use padding to maintain gap between controls, don’t put spaces.
8) Page Design layout should have a main table (1Row X 1Column) with height & width as 100%, and inner table within this table (of fixed width if required). Main table should have all content within it to be center aligned.
9) The applications should be designed to be displayed on “1024 X 768” screen resolution.
10) The page margins should be set to zero otherwise a default value is taken.
11) Always try to avoid horizontal scrollbar in a page.
12) Use Application path defined in web.config for page redirection.
13) Preload images on page.
14) Specify cell spacing and cell padding wherever required otherwise default value is considered.
15) Decide between using pixel width or % width as both have different looks at different resolution.
16) <span> tag does not work in Firefox. Use <div> instead.
17) Comment HTML code wherever possible.
18) Ensure that target page name in URL is entered as Case Sensitive (for Linux Servers).
19) Use relative path to refer a location, never use physical path.
20) CSS Class Names should be descriptive and use camel case e.g. tableWidth.
21) CSS Classes specific for tags should have Tag Name in the class name.
22) CSS classes specific for elements should have Element ID in the class name.
23) All files name must be different (e.g Pa ge name and class name must be different)

Javascript Related
1) Check Script Code in IE and Firefox.
2) Put validator to check <, > or ‘(if not expected, if required). This helps prevent SQL injection.
3) Comment your code for every 10~15 lines explaining the logic performed.
4) For functions add comment to explain its arguments, return type & purpose (short but explanatory).
5) Every function should contain the credentials of the creator/ modifier.
6) Use Regular Expressions to validate controls (Java script/ server side) if needed.
7) Always enclose Javascript with HTML comments i.e. within the html comments () tag.
8) Using AJAX, if something is processed in background, show an indication (e.g. loading image).
9) When using parseInt always use the base as 10 (i.e. parseInt(,10)).
10) Create a js file for common functions used within the application.
11) When storing value in a javascript variable always check for a new line character and replace it with “
” or “\n”.


Database Related
1) Use Stored procedures (if possible) as they are precompiled.
2) No hard deletion wherever possible – Instead maintain a status field.
3) Use Transactions – commit, rollback - when executing a bunch of queries together.
4) For each record in database maintain: Creation time - GMT (GetUTCDate()) & status(deleted).
5) Do not use * in select statement. Always specify field names.
6) Don't use cursors if the same logic can be achieved by using SELECT, UPDATE or DELETE.
7) Don't do SELECT max(ID) from Master when inserting in a Detail table. Use one of SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY.
8) Try to use “where” condition instead of “join” to filter out records.
9) Use sub queries wherever possible instead of a single select by joining more number of tables.
10) Always append the Project abbreviation as prefix of Table Name.
11) Stored procedure names should explain the task performed (e.g. CustomerGetByID).
12) Try to make single stored procedure for both Insert & Update for each table.
13) Always ensure that SQL Keywords are in capital e.g. SELECT FirstName FROM Contacts.
14) Comment each Stored Procedure - functionality performed, Created by, Created on, updated by, updated on, reason of updating.
15) Data type and length of fields should be logical (i.e. related with the task).

.NET (Code & Design) Related – Basics
1) The Project should be linked to VSS Database from Day 1.
2) Always put your signature on the code you had worked on (name, date).
3) Follow naming conventions for naming all the controls, global & local variables.
4) For functions add comment to explain its arguments, return type & task performed (short but explanatory).
5) Every function should contain the credentials of the creator/ modifier (Created by, Created on, updated by, updated on, reason of updating).
6) Create generalized functions for code reuse. Try to modularize the code as much as possible.
7) Always backup your project and database at regular intervals.
8) Use data link layer for communicating with the database server (DAL).
9) Always check for DBNull/NULL values (try to check from database by using ISNULL()).
10) Try to create common parts as User Control.
11) Try not to code based on presumed values. Try to consider scenarios where value may differ.
12) Do not refer elements of dataset by index number, always use name of field.
13) Use relative path to refer a location, never use physical path.
14) Maintain the release version number of application before deploying or releasing.
15) Server trips should be minimized.
16) Keep in mind the upper limit of the data type when using Convert functions.
17) Use Enum and constants wherever required for defining True, False etc.
18) Analyze the pros and cons of Server.Transfer and Server.Execute before using them.
19) Use case instead of if else ladder.
20) Check tab order of the page before release.
21) Always close database connections after usage.
22) Use #region to group related pieces of code together.
23) Always watch for unexpected values.
24) Comment your code for every 10~15 lines explaining the logic performed.
25) At application start up, do "self check" and ensure all required files and dependencies are available in the expected locations.
26) Check for database connection at start up, if required.
27) When fetching record from table, check the datatable contains at least one row before using it.
28) Use the AssemblyInfo file to provide assembly information.
29) If database connection, socket, I/O stream is opened, always close them in the finally block.
30) Use StringBuilder class instead of String when manipulating string objects.
31) Make the code modular, break large system into small blocks.
32) Convert strings to lower/upper case before comparing if case insensitive matching is needed.
33) Never hardcode path in code. Get the application path programmatically and use relative path or from Web.Config.
34) Always try to avoid exceptions by checking all the error conditions programmatically.
35) Decide a standard way of page to page data transfer. It can be done using Session, Querystring, Previouspagetype or HttpContext (if it is appropriate).
36) For simple data binding use DataReader. It is faster then DataSet , DataTable or DataView.
37) Use classes for Insertion/updation in database. Keep Property name same as database field (BAL).
38) On inserting value in a String type column always replace single quote with two single quotes.
39) Try to make the code very simple
40) Simplicity, organizing code properly, good design makes code more reliable and bug free.
41) Always maintain the code formatted and indented (to make it more readable).

Error & Exception Handling
42) All the code should be written inside a try catch finally block.
43) Don’t use try-catch-finally constructs inside hot-spots (i.e. loops and such) if it can be avoided.
44) Never do a 'catch exception and do nothing'.
45) Handle Exceptions and keep a log track in database.
46) When re-throwing an exception, use throw statement without specifying the original exception.
47) Error messages must be user understandable format and should be consistent.
48) All errors must be displayed in a common place in all forms.
49) Error messages, in addition to telling what is wrong, should also tell what the user should do.
50) Try to use the specific exception error handlers instead of generalized ones.

Session, Viewstate, Application and Querystring Variables
51) Usage of Session and Application variables should be minimal.
52) Store Session value in a variable at page load and use the variable across the page.
53) Check for Session timeout on each page load and redirect as required.
54) Sensitive information stored in viewstate should be always encrypted.
55) Store information in Viewstate only when required.
56) Sensitive information passed to any page through Querystring should be encrypted.
57) For storing large data use session instead of viewstate.
58) Clear all the session variables which are not required further.

Configuration Settings
59) Connection string should be defined in web.config.
60) Define culture (eg. EN-GB for Great Britain) of the application (if required).
61) Define Application path in web.config for page redirection (if required).

Classes & Methods
62) Make the member variables “private” instead of public/protected. Expose public/protected Properties to access them.
63) The event handler should call another method to perform the required action.
64) Avoid passing too many parameters to a method.
65) If method has more than 5 parameters, try to define a class or structure.
66) If a method returns a collection, return an empty collection instead of null, if there is no data.
67) Method name should describe its functionality. Do not use mis-leading names.
68) A method should do only one job. Don’t combine more than one job even if jobs are very small.
69) If we pass the values to the class from outside make property for that.

.NET (Code & Design) Related – Advanced

70) All the error messages displayed to the end user should come from a Xml file.
71) Do not hardcode strings. Use resource files.


Naming Conventions
1) Follow the below stated naming convention:
Pascal Casing – For defining Class names, Method names, Namespace, Property
- First character of each word is Uppercase and rest characters are lower case.
Example: BackColor
Camel Casing – For variable names and method parameters - First character of each word, except the first word is Uppercase and rest characters are lower case.
Example: backColorPattern
2) Use descriptive words to name variables. Do not use abbreviations.
Example: strAddress instead of strAddr
3) Never use variable names like i, n. Use meaningful names - intIndex, intCounter.
4) Do not use underscores (_) for local variable names.
5) Do not use variable names that resemble keywords.
6) Prefix boolean properties and methods with “is” or similar prefixes – isDeleted, IsNumber().
7) All control’s should be named with the related prefix followed by column name in the database.



Please Note: Each and every Class, Function, Modules, Stored Procuredures should contain the following credentials at the top:
/*
Created By –
Created On –
Updated By –
Updated On –
Reason for Updating –
*/

Also adds comments at the top explaining the arguments, return type & task performed.

Friday, June 3, 2011

Custom Paging in asp.net

Implement Custom Paging in ASP.NET

In ASPX Page:

<asp:DataList runat="server" ID="dListItems" CellPadding="2">
<ItemTemplate>
<%#Eval("title") %>
</ItemTemplate>
<AlternatingItemStyle BackColor="Silver" />
<ItemStyle BackColor="White" />
</asp:DataList>


<tr>
<td>
<table cellpadding="0" border="0">
<tr>
<td align="right">
<asp:LinkButton ID="lbtnFirst" runat="server" CausesValidation="false" OnClick="lbtnFirst_Click">First</asp:LinkButton>
 </td>
<td align="right">
<asp:LinkButton ID="lbtnPrevious" runat="server" CausesValidation="false" OnClick="lbtnPrevious_Click">Previous</asp:LinkButton>  </td>
<td align="center" valign="middle">
<asp:DataList ID="dlPaging" runat="server" RepeatDirection="Horizontal" OnItemCommand="dlPaging_ItemCommand"
OnItemDataBound="dlPaging_ItemDataBound">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnPaging" runat="server" CommandArgument='<%# Eval("PageIndex") %>'
CommandName="Paging" Text='<%# Eval("PageText") %>'></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
</td>
<td align="left">
  <asp:LinkButton ID="lbtnNext" runat="server" CausesValidation="false"
OnClick="lbtnNext_Click">Next</asp:LinkButton></td>
<td align="left">

<asp:LinkButton ID="lbtnLast" runat="server" CausesValidation="false" OnClick="lbtnLast_Click">Last</asp:LinkButton></td>
</tr>
<tr>
<td colspan="5" align="center" style="height: 30px" valign="middle">
<asp:Label ID="lblPageInfo" runat="server"></asp:Label></td>
</tr>
</table>
</td>
</tr>

In CS Page:

#region Private Properties
private int CurrentPage
{
get
{
object objPage = ViewState["_CurrentPage"];
int _CurrentPage = 0;
if (objPage == null)
{
_CurrentPage = 0;
}
else
{
_CurrentPage = (int)objPage;
}
return _CurrentPage;
}
set { ViewState["_CurrentPage"] = value; }
}
private int fistIndex
{
get
{

int _FirstIndex = 0;
if (ViewState["_FirstIndex"] == null)
{
_FirstIndex = 0;
}
else
{
_FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
}
return _FirstIndex;
}
set { ViewState["_FirstIndex"] = value; }
}
private int lastIndex
{
get
{

int _LastIndex = 0;
if (ViewState["_LastIndex"] == null)
{
_LastIndex = 0;
}
else
{
_LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
}
return _LastIndex;
}
set { ViewState["_LastIndex"] = value; }
}
#endregion

#region PagedDataSource
PagedDataSource _PageDataSource = new PagedDataSource();
#endregion

#region Private Methods
/// <summary>
/// Build DataTable to bind Main Items List
/// </summary>
/// <returns>DataTable</returns>
private DataTable GetDataTable()
{
DataTable dtItems = new DataTable();

DataColumn dcName = new DataColumn();
dcName.ColumnName = "title";
dcName.DataType = System.Type.GetType("System.String");
dtItems.Columns.Add(dcName);

DataRow row;
for (int i = 1; i <= 100; i++)
{
row = dtItems.NewRow();
row["title"] = "Sample Row: I am putting here sample text for row " + i;
dtItems.Rows.Add(row);

}
return dtItems;

}

/// <summary>
/// Binding Main Items List
/// </summary>
private void BindItemsList()
{

DataTable dataTable = this.GetDataTable();
_PageDataSource.DataSource = dataTable.DefaultView;
_PageDataSource.AllowPaging = true;
_PageDataSource.PageSize = 2;
_PageDataSource.CurrentPageIndex = CurrentPage;
ViewState["TotalPages"] = _PageDataSource.PageCount;

this.lblPageInfo.Text = "Page " + (CurrentPage + 1) + " of " + _PageDataSource.PageCount;
this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
this.lbtnFirst.Enabled = !_PageDataSource.IsFirstPage;
this.lbtnLast.Enabled = !_PageDataSource.IsLastPage;

this.dListItems.DataSource = _PageDataSource;
this.dListItems.DataBind();
this.doPaging();
}

/// <summary>
/// Binding Paging List
/// </summary>
private void doPaging()
{
DataTable dt = new DataTable();
dt.Columns.Add("PageIndex");
dt.Columns.Add("PageText");

fistIndex = CurrentPage - 5;


if (CurrentPage > 5)
{
lastIndex = CurrentPage + 5;
}
else
{
lastIndex = 10;
}
if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
{
lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
fistIndex = lastIndex - 10;
}

if (fistIndex < 0)
{
fistIndex = 0;
}

for (int i = fistIndex; i < lastIndex; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt.Rows.Add(dr);
}

this.dlPaging.DataSource = dt;
this.dlPaging.DataBind();
}
#endregion


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindItemsList();
}
}
protected void lbtnNext_Click(object sender, EventArgs e)
{

CurrentPage += 1;
this.BindItemsList();

}
protected void lbtnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
this.BindItemsList();

}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("Paging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
this.BindItemsList();
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Style.Add("fone-size", "14px");
lnkbtnPage.Font.Bold = true;

}
}
protected void lbtnLast_Click(object sender, EventArgs e)
{

CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
this.BindItemsList();

}
protected void lbtnFirst_Click(object sender, EventArgs e)
{

CurrentPage = 0;
this.BindItemsList();


}

404 error page not found

Implement 404 functionality in ASP.NET

<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" /> </customErrors>

<configuration>
<system.webServer>
<httpErrors errorMode="Custom" >
<remove statusCode = "404" subStatusCode="-1" />
<error statusCode = "404" prefixLanguageFilePath="" path="FileNotFound.htm" responseMode="Redirect" />
</httpErrors>
</system.webServer>
</configuration>

how to take a site offline

how to take a site offline in ASP.NET

It is very simple to make the website offline. Means when any person type the url of any page. a default page will open instead of what url typed.

You can achieve this by making a HTML page having named App_Offline.htm and upload it into the root directory that automatically makes your site offline.

How to Empty Controls in .net

How to Empty Controls in ASP.NET

///

/// Empty Controls in the page.
///

private void EmptyControl()
{
foreach (Control ctrl in this.Form.Controls)
{
if (ctrl is ContentPlaceHolder)
{
ContentPlaceHolder chp = ((System.Web.UI.WebControls.ContentPlaceHolder)ctrl);
foreach (Control ctrl2 in chp.Controls)
{
if (ctrl2 is TextBox)
{
TextBox tb = ((System.Web.UI.WebControls.TextBox)ctrl2);
tb.Text = "";
}
if (ctrl2 is DropDownList)
{
DropDownList dl = ((System.Web.UI.WebControls.DropDownList)ctrl2);
dl.SelectedIndex = 0;
}
if (ctrl2 is CheckBoxList)
{
CheckBoxList dl = ((System.Web.UI.WebControls.CheckBoxList)ctrl2);
dl.ClearSelection();
}
if (ctrl2 is CheckBox)
{
CheckBox dl = ((System.Web.UI.WebControls.CheckBox)ctrl2);
dl.Checked = false;
}
}
}

}
}

Move Files from one folder to another

Move Files from one folder to another in ASP.NET

You can move files from one folder to another by using the below code
using System.IO;

DirectoryInfo dirInfo1 = new DirectoryInfo("D:Folder1");
DirectoryInfo dirInfo2 = new DirectoryInfo("D:Folder2");

FileInfo[] Folder1Files = dirInfo1.GetFiles();
if (Folder1Files.Length > 0)
{
foreach (FileInfo aFile in Folder1Files)
{
if (File.Exists("D:Folder2" + aFile.Name))
{
File.Delete("D:Folder2" + aFile.Name);
}
aFile.MoveTo("D:Folder2" + aFile.Name);
}
}

How to check Null Value

How to check Null Value in ASP.NET

The solution to check the Null Value without using DBNull is a trick
Concatenate "" with null which makes it Blank then check blank value
i.e if(null+"" == ""){ //statement};

How to show Confirm Message in JavaScript

How to show Confirm Message in JavaScript


Confirm message is used when there is choice to user whether he wanted to go ahead or not. It is client side message JavaScript must be enable to display this message.

<script language='javascript' type='text/javascript'>

function ConfirmMessage()
{
if(confirm("Your Message."))
{
return true;
}
else
{
return false;
}
}


</script>


<asp:LinkButton ID="lnkConfirmMessage" OnClientClick="ConfirmMessage();" runat="server">ConfirmMessage</asp:LinkButton>

how to show alert message

how to show alert message


Response.Write("<script language='javascript'>alert('Your Message!')</script>");

OR

string script = "<script language='javascript'>alert('Your Message!');</script>";
ClientScript.RegisterStartupScript(typeof(Page), "Message", script);

OR

Call function when page is load

Page.RegisterStartupScript("onload", "<script language='javascript' type='text/javascript'>functionname();</script>");

OR

<script language='javascript' type='text/javascript'>
function ShowAlert() {
alert('Your Message!');
return false;
}
</script>

<a href="#" onclick="javascript:ShowAlert();">ShowAlert</a>

Thursday, June 2, 2011

how to open pop up

how to open pop up

<script language="javascript" type="text/javascript">
function OpenWindow() {
window.open("http://learnlogic.blogspot.com/", "learnlogic", "location=1,status=1,scrollbars=1,width=600,height=600");
}
</script>


<a href="#" onclick="javascript:OpenWindow();">OpenWindow</a>

Autongenerate Serial Number in grid

Autongenerate Serial Number in grid


Automatically generate serial number at run time no need to bind with data use the below code for showing serial number in grid.

<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>

Remove Mac Error

Remove Mac Error

You can remove Mac error by using below code
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode ="Never" />

How to make default button in page

How to make default button in page

Default button means whenever you press the enter button then event of that button would be fired. If in a page more than one button then you can make anyone to be default button. Some time when there is no default button in the page then user press the default button by mouse not by keyword so default button save the time of user.

protected void Page_Load(object sender, EventArgs e)
{
      Form.DefaultButton = ButtonID.UniqueID;
}

OR


<body defaultButton="ButtonID">