Tuesday, November 1, 2011

Valid Number

 

Valid Number Validation in JavaScript

You can use this code to validate Number and Required field validation. Put validation on Text Box. On Click of submit button this code will check whether Text Box is empty or not if Text Box is empty then it show message. It will also check the valid number when Text Box has any text in it. It will show message when number is not valid.

Insert this code between Head section of the Page.

<script language="javascript" type="text/javascript">
//<![CDATA[
   function IsValNumber(strControlName)
{

var strValue=document.getElementById(strControlName).value;
if (strValue.length > 0)
{
var rgeExp = /[^0-9]/ ;
   
if (document.getElementById(strControlName).value.search(rgeExp) >= 0) { alert("Non-numeric character(s) and space(s) are not allowed in"); return false; }
else { alert("Valid number"); return true; } } else { alert("Please enter any number"); return false; } } //]]> </script>

Insert this code between Body Tag.

<div>
<asp:TextBox ID="txtSubmit" runat="server"></asp:TextBox><asp:Button ID="btnSubmit"
runat="server" OnClientClick="javascript:return IsValNumber('txtSubmit');" Text="Submit" />
</div>

How to validate an email

 

How to validate an email address using JavaScript

You can use this code to validate Email ID and Required field validation. Put validation on Text Box. On Click of submit button this code will check whether Text Box is empty or not if Text Box is empty then it show message. It will also check the valid email Id when Text Box has any text in it.

Insert this code between Head section of the Page.

<script language="javascript" type="text/javascript">
//<![CDATA[
function IsValEmail(strControlName)
{

var stremail=document.getElementById(strControlName).value;
if (stremail.length > 0)
{
var rgeExp = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/ ;
if (document.getElementById(strControlName).value.search(rgeExp) < 0)
{
alert("Please enter valid E-mail Id");
return false;
}
else
{
alert("Valid E-mail Id");
return true;
}
}
else
{
alert("Please enter E-mail Id");
return false;
}
}
//]]>
</script>

Insert this code between Body Tag.

<div>
<
asp:TextBox ID="txtSubmit" runat="server"></asp:TextBox><asp:Button ID
="btnSubmit"
runat="server" OnClientClick="javascript:return IsValEmail('txtSubmit');" Text
="Submit" />
</
div>

Saturday, September 17, 2011

Export Dataset to Excel in ASP.NET

 

Export grid to Excel. You can export the grid to excel sheet and give option to Save or Download
 the Excel Sheet.
In CS Page use the below code:
        DataClass objDataClass = new DataClass();
DataSet ds = objDataClass.GetDate();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SearchResults.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";

System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);

//Grid ID
gvDisplay.RenderControl(hw);

Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
In Aspx page use EnableEventValidation="false" in page directive

Increase number of connection to database

 Increase number of connection to database from ASP.NET

 Write below code in your web config file

<add key="ConnectionString" value="Data Source=servername;User ID=sa; Password=pass@123;
 Initial Catalog=databasename; Max Pool Size=400;" />

Maximum upload size in ASP.NET


How to increase the file upload size in Asp.Net

In asp.net you can only upload the file of 4mb size 

but you can increase the limit of upload file by using the below code
 
<system.web>
  <httpRuntime maxRequestLength="2097151" useFullyQualifiedRedirectUrl="true" executionTimeout="2600" />
</system.web>

How to increase session timeout in asp.net


Increase session timeout in ASP.NET by using this code. Put this code in web.config file. 
 
<system.web>
<!-- Increase session timeout  -->
<sessionState mode="InProc"  stateConnectionString="tcpip=127.0.0.1:42424"  cookieless="false"   
  timeout="120"/>
</system.web>
This will increase the session timeout to 120 min. By default session timeout is 20 min 
 
or
 
<system.web>
  
    <sessionState mode="StateServer" stateNetworkTimeout="10" 
sqlCommandTimeout="30" cookieName="ASP.NET_SessionId" timeout="53200" 
regenerateExpiredSessionId="False">
      <providers>
        <clear/>
      </providers>
    </sessionState>
    <httpRuntime executionTimeout="9999" maxRequestLength="10240"/>
    <machineKey validationKey="409B3A07F360A34A7C5DDD40B317AF7BBD7904A1E3D68273A9AC320BAE312D39619A28443AAF92E16A88BC66BF5AAF543C33723581EAD1378DEA9653C44868FC" 
decryptionKey="EA09335756D695E538762FABB50FE581AFA525C4B485AC51E450D95DD813303E" 
validation="SHA1" decryption="AES" />
    </system.web>
 
 

Generate your Machine Key 
it will be unique so generate your own key from the below link and 
paste in web.config file


http://aspnetresources.com/tools/machineKey
 
in global.asax
 void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started
        // Code that runs when a new session is started
        Session.Timeout = 53200;
    }

Sunday, July 31, 2011

Difference Between Structure and Class?

Difference Between Structure and Class?


Structure

Class

Structure is a Value type and stored in stack.

Class is a reference type and stored in heap.

Structures do not support inheritance.

Classes support inheritance.

By default all members of Structure are public.

In case of Class, all constants and variables are private while other members of
the Class are public by default.

Structure members can't be declared Protected.

Class members can be declared Protected.

A Structure cannot be fully empty.

A Class can be fully empty.

A Structure does not need a constructor.

A Class needs a constructor.

Finalize method is never called for Structures as they are never terminated.

Finalize method is called for Classes as they are terminated by GC (Garbage collector)
that calls the Finalize method.

Even after assigning the value nothing to a Structure variable, instance continues
to be associated with the variable and we can access its data members.

In Class, if we assign nothing to object variable we cannot access any member through
the variable until you assign another instance to it.

Boxing of a Structure object creates a copy of the object in a different type.

Boxing a Class object creates a reference (of different type) to the same object.

Structure are value type it is not possible to assign null to a Structure object.

Classes are reference type so it is possible to assign null value to Class object.

Differences between an interface and an abstract class?

Difference Between an Interface and an Abstract class?


Interface

Abstract class

An Interface is used to define methods (have no Body) but not for the implementation.

An Interface abstract class can be used to implement the Methods.

An Interface allows us to use multiple inheritance.

An Abstract Classes does not allows us to use multiple inheritance.

Interfaces are slow.

Abstract classes are fast.

When we have similar classes that will share code use an abstract class.

When we have classes that are nothing to do with one another but share some aspect
that they do not share a common ancestor then use an interface.

An Interface cannot implement methods.

An abstract class can implement methods.

An Interface can only inherit from another Interface.

An abstract class can inherit from a class and one or more interfaces

An Interface cannot contain fields.

An abstract class can contain fields.

An Interface can contain property definitions.

An abstract class can implement a property.

An Interface cannot contain constructors or destructors.

An abstract class can contain constructors or destructors.

An Interface can be inherited from by structures.

An abstract class cannot be inherited from by structures.

An Interface can support multiple inheritances.

An abstract class cannot support multiple inheritances.

Tuesday, July 26, 2011

Help File Generation for ASP.NET Website Project

Help File Generation for ASP.NET Website Project(Using Sandcastle)



It is very easy to create a help file. If you have followed the practice of putting standard XML comments into your .NET code, for code commenting, install Ghost Doc which is available at http://submain.com/download/ghostdoc/. After installation right click on the code and click on “Document This” which will automatically insert the commenting structure like:
     /// <summary>
     ///
     /// </summary>
     /// <returns></returns>
 It is very easy to generate help file based on that. Here are the steps to achieve this
1.       Install Sandcastle from here: http://sandcastle.codeplex.com/
2.       Install Sandcastle Help File Builder GUI from here: http://shfb.codeplex.com/
3.       Install HTML Help 1.x Compiler from here: http://go.microsoft.com/fwlink/?LinkId=14188
4.       Download the EWSoftware.CodeDom.dll from here: http://sandcastlestyles.codeplex.com/releases/view/22689
Add a reference to the above mentioned dll in your project.
5.       Add the following  to the <compilers> section within <system.codedom> section of the web.config:
<compiler language="c#;cs;csharp" extension=".cs"
          compilerOptions="/docpath:C:\Publish\Docs"
          type="EWSoftware.CodeDom.CSharpCodeProviderWithDocs,
              EWSoftware.CodeDom, Version=1.1.0.0, Culture=neutral,
              PublicKeyToken=d633d7d5b41cbb65">           
            <providerOption name="CompilerVersion" value="v3.5"/>
</compiler>
Publish the website. The XML Documentation files would be generated and can be found in the folder specified in /docpath.
              
6.       Start Sandcastle Help File Builder GUI. Go to Project Explorer. Click on Document Sources -> Add Document Source. Browse and add the App_Code.dll file and the .xml file from the /docpath folder to the project.
You may want to alter the following properties in the Project Properties window:-


Property Name
Description
HelpTitle
The title for the help file
OutputPath
The path where the help file will be generated
ShowMissingNamespaces
If set to true a message is added to the namespace help topics if the namespace comments are missing.
ShowMissingValues
If set to true a message is added to the help topic if the <value> tag is missing.
APIFilter
Used to include /exclude elements from the help file.
Note: If App_Code classes are not contained within a namespace; manually select them here to make them visible in Help file.

7.       Click on Documentation -> Build Project to generate the help file.
8.       After the build process is complete, click on Documentation -> View Help File -> View Help file.

Sunday, July 24, 2011

FREE ASP.NET TOOLS

FREE ASP.NET TOOLS


Here is a list of some great tools and add-in that every .NET developer must have:

  • Code Compare
    Visual Studio plug-in for code comparison. This is used to compare two files. This
    will automatically compare each contents of each file and tells you the difference
    between these files.
    http://www.devart.com/codecompare/

  • Resharper
    It is a kind of tool which makes easy the development environment of Visual Studio.
    It save lot of time and also guide you while coding it inspect your code at real-time.
    This maintains the standard of your code not.
    http://www.jetbrains.com/resharper/

  • SSMS Tools Pack
    Plug-in for SQL Server Management Studio that adds a good deal of functionality.
    It adds the intelligence and formatting of script which will save the time of the
    developer.
    http://www.ssmstoolspack.com/

  • LINQ Pad
    A fantastic learning tool for those who are just getting into LINQ or for those
    who want a code snippet IDE to execute any C# or VB expression.
    http://www.linqpad.net/

  • Design Patterns
    Design pattern are the solution of software development problem. Each time we face
    the same problem in the software to resolve this there must be some design pattern
    while developing the application
    http://www.dofactory.com/Patterns/Patterns.aspx

Friday, July 15, 2011

Reset Identity value of a column in SQL Server

Reset Identity value of a column in SQL Server


You can reset the identity of a column in SQL Server table. Identity column means
whose value increase automatically whenever you insert a record. But when you delete
all the records from the table and insert a new record then value of identity column
will be one(increment seed) more than the last value not starting from one. In this
situation we want to start value from 1 or any another number after deleting the
data. To reset the identity value use the below command

Suppose I have a table whose name is Login then to reset identity I can use this
command

DBCC CHECKIDENT ([Login], RESEED, 0)

To Check identity value use the below command

DBCC CHECKIDENT ([Login], NORESEED)

If you are using an identity column in SQL Server tables, you can set the next insert
value to whatever value you want.

To set the value of the next ID to be 100, you can use this command:

DBCC CHECKIDENT ([Login], RESEED, 99)

Note that the next value will be whatever you reseed with here we use + 1, so in
this case I set it to 99 so that the next value will be 100.

Wednesday, July 6, 2011

Select random rows with Microsoft SQL Server?

Select random rows in SQL Server

SELECT Top 10* FROM [Table Name] ORDER BY NEWID()

You can select top 10 random rows by the above query each time you can get different 10 rows. This query randomly select data each time when you execute query.




Count number of tables, stored procedure, function and views in sql database

Count number of tables, stored procedure, function and views in sql database

To count number of Tables in sql database
SELECT COUNT(*) FROM information_schema.tables WHERE Table_Type = 'Base Table'

To count number of Procedures in sql database
SELECT COUNT(*) FROM information_schema.routines WHERE Routine_Type = 'Procedure' 

To count number of Functions in sql database
SELECT COUNT(*) FROM information_schema.routines WHERE Routine_Type = 'Function' 

To count number of Views in sql database
SELECT COUNT(*) FROM information_schema.views

Tuesday, July 5, 2011

Turning On and Off Identity Column in SQL Server

Turning On and Off Identity Column in SQL Server

General Form
SET IDENTITY_INSERT table name ON
GO

--Sql Insert Statement here
SET IDENTITY_INSERT table name OFF
GO
When you transfer data from one table to another table using script
then you should first on the identity field of the table by using the below query 

SET IDENTITY_INSERT table name ON


Now you can write insert statement for inserting data into another table. After inserting the data into another table you should off the identity field of the table

SET IDENTITY_INSERT table name OFF

SEO Best Practices


SEO Best Practices


(SEO Best Practices for ASP.NET Web Applications)
  • Provide unique, accurate page Title. Do NOT use stop words like “.com”, particularly
    at the beginning of the Title text.
      Tips:
    • · Have unique title for each page.
    • · Use keywords in title.
  • Include proper Description Meta tags and use meaningful keywords.
  • Standardize the structure of page URLs. Organize pages into categories.
  • Ensure that all the links in your site follow same URL casing format.
    (For example, always use lowercase letters.)
  • Add an <h1> tag to the <body> section of the page to improve page relevancy.
    Use only one <h1> tag per page.
  • Make site navigation easier.
    • Tips:
    • · Use bread crumbs on pages
    • · Use relevant Sitemap
    • · Remove all broken links
  • Create a custom 404 page to be displayed when ‘page is not found’ error occurs.
  • Place an effective Robots.txt file on your server. It tells search engines what
    parts of your website should be indexed and what areas or pages should not be indexed.
  • If pages are still not being indexed, submit them to popular search engines like
    Google, Yahoo, etc. For example, for Google, you may submit a page to be indexed
    at google.com/addurl.

Insert Horizontal Lines in Word Documents Quickly

Insert Horizontal Lines in Word Documents Quickly

 

--- Thin line
Insert three or more times hyphen (-) and then press enter key 
Output will be as below



 
*** Broken line
Insert three or more times star (*) and then press enter key 
Output will be as below
 
 
### Thick line with two thin lines
Insert three or more times hash (#) and then press enter key 
Output will be as below
 
=== Double line
Insert three or more times equal to (=) and then press enter key 
Output will be as below
 
~~~ Wavy line
Insert three or more times tilde (~) and then press enter key
Output will be as below
 
 

Monday, July 4, 2011

How To Generate Dummy Text In Word 2007

How To Generate Dummy Text In Word 2007

General Representation of creating dummy text in word 2007

=Lorem(Number of Paragraphs, Number of Lines)

=Lorem(Number of Paragraphs)

=Lorem()

OR

=Rand(Number of Paragraphs, Number of Lines)

=Rand(Number of Paragraphs()

=Rand()

Parameters are optional. You can generate dummy text by using any of the above formula. After writing formula press enter key.

Suppose you want to generate dummy text with 3 paragraph and 3 lines (Line are the complete sentence) per paragraph.

You can use this formula =Rand(1,1) or =Lorem(1,1)

Note: Formula should be the first sentence of the line and after writing formula you must have to press enter key. In this way you can generate the dummy text in quick time.

Saturday, July 2, 2011

How to disable Text Area resizing

Error: Multiline Textbox resizable in Firefox and Chrome

<asp:TextBox ID="TextBox1" style="Resize:none;" TextMode="MultiLine" runat="server">
</asp:TextBox>

Using the above Style you can restrict Multiline Textbox from resizing.

Friday, July 1, 2011

Difference Between Asp.Net 2005 and Asp.Net 2008

Difference Between Asp.Net 2005 and Asp.Net 2008


ASP.NET 2005

ASP.NET 2008

32 bit support

64 bit support

Asp.net 2.0 includes the following as new features
  • Master pages
  • Grid View
  • Profiles

Asp.net 3.5 includes the following as new features
  • List View control
  • Data pager control
  • Nested master pages
  • LINQ Data Source Control.
Asp.net 2.0 does not support multi targeting environment. Asp.net 3.5 Support multiple targeting option that we choose from the dropdown list whether to have visual studio 2008 build application against the asp.net 2.0, 3.0, 3.5 frameworks
There is no inbuilt support for ajax you have to explicitly download and installed the software. In asp.net 3.5 ajax is integrated into the framework, thereby making the process of building intuitive cool user interfaces easier.
It does not support silverlight It supports silverlight.
It does not provide javascript debugging. It provide javascript debugging
It does not support LINQ It support language intergrated query (LINQ)
Only source and design view Source, design and split view.

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.