Tuesday, October 18, 2011

Common Connection String for All Database(Sql,MySql,Oracle ,Access....)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;
namespace SearchEngine.QueryExecutor
{
    public class DataAccess
    {
        //Input
        public string inConnectionString = "";
        public string inProviderName = "";

        IDbConnection objConnection;
        IDbCommand objCommand;
        IDbDataAdapter objAdapter;
        IDbTransaction objTransaction;
        DbProviderFactory objProvidersFactory;

        DataSet dsData;
        DataTable dtData;
     
        private void GetMysqlConnection()
        {
            try
            {
                objProvidersFactory = DbProviderFactories.GetFactory(inProviderName);
                objConnection = objProvidersFactory.CreateConnection();
                objConnection.ConnectionString = inConnectionString;
                objConnection.Open();    
            }
            catch (System.Exception Ex)
            {
                objConnection = null;
            }

        }
     
     
        #region EXECUTE DATASET
        public DataSet ExecuteDataSet(CommandType cmdType, string CommandText)
        {
            try
            {
                dsData = new DataSet(); // Create new instance to dsData
                GetMysqlConnection();
                if (objConnection != null)
                {
                    objTransaction = objConnection.BeginTransaction();

                    objCommand = objProvidersFactory.CreateCommand();

                    //objCommand.CommandText = "select * from tbl_int_category";
                    objCommand.CommandTimeout = 0;
                    objCommand.CommandText = CommandText;
                    objCommand.CommandType = CommandType.Text;
                    objCommand.Transaction = objTransaction;
                    objCommand.Connection = objConnection;
                    objAdapter = objProvidersFactory.CreateDataAdapter();

                    objAdapter.SelectCommand = objCommand;

                    objAdapter.Fill(dsData);
                    objTransaction.Commit();
                }
            }
            catch (System.Exception Ex)
            {
                objTransaction.Rollback();
                dsData = null; // If any errors found then ,assign the NULL value to dsData(DataSet)
            }
            finally
            {
                if (objConnection != null)
                    objConnection.Close(); // Close the Database connection
            }
            return dsData; // Return the DataSet(dsData);


        }
        #endregion
     




    }
}

Thursday, October 13, 2011

While developing any web site, one should keep some points in mind.

1) Set debug=false under compilation as follows:

2) Use Server.Transfer instead of Response.Redirect.

3) Always check Page.IsValid when using Validator Controls

4) Use Foreach loop instead of For loop for String Iteration.

5) Use Client-Side Validation. (but not all the time you have to validate even on the server side)

6) Check “Page.IsPostBack”. To avoid repetition code execution.

7) GIF and PNG are similar, but PNG typically produces a lower file size. (True, but some browsers not supporting PNG format)

8) Use the AppOffline.htm when updating binaries

9) Turn off Tracing unless until required. (by default it's off, use on the pages where it's required)

10) Precompiled pages and disable AutoEventWireup; setting the AutoEventWireup attribute to false in the Machine.config file.

11) Turn off Session State, if not required.

12) Select the Release mode before making the final Build for your application.

This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug

13) Disable ViewState when not required.

EnableViewState="false"

14) Avoid frequent round trips to the Database.

15) Use Caching to improve the performance of your application.

16) Validate all Input received from the Users.

17) Use Finally Method to kill resources. (But not in the case of using)

18) The String and Stringbuilder Magic.

It is nice to use Stringbuilder instead of String when string are Amended. Strings occupy different memory location in every time of amended where stringbuilder use single memory location

19) Never use object value directly; first get object value in local variable and then use. It takes more time then variable reading.

20) Avoid Exceptions: Use If condition (if it is check proper condition)

21) Code optimization: Avoid using code like x = x +1; it is always better to use x+=1.

22) Data Access Techniques: DataReaders provide a fast and efficient method of data retrieval. DataReader is much faster than DataSets as far as performance is concerned

23) Before doing a bulky ASP code processing, you can check to make sure Response.IsClientConnected.

24) As always, avoid session variables because each ASP page runs in a different thread and session calls will be serialized one by one. So, this will slow down the application. Instead of session variables you can use the QueryString collection or hidden variables in the form which holds the values.

25) Enabling buffering will improve the performance, like

<% response.buffer=true %>

Then use:

<% response.flush=true %> 

26) Use Repeater control instead of DataGrid , DataList, Because It is efficient, customizable, and programmable.

27) Data listing is more time consume when large data are retrieve from database.

Paging will display only particular data but take load of all data.

Fetch only data that is needed for current page.

28) Avoid Inline JavaScript and CSS

29) Use single css file instead of multiple css file.

Try your best to combine all your CSS based classes into a single .css file as lot of .css files will cause a large amount of requests, regardless of the file sizes.

.css files are normally cached by browsers, so a single and heavy .css file doesn’t cause a long wait on each page request.

Inline .css classes could make HTML heavy, so again: go ahead with a single.css file.

30) Reduce cookie size

31) Compress CSS, JavaScript and Images

Online compressors are available; to compress file please refers following web and Replace your file content with optimize code.

http://iceyboard.no-ip.org/projects/css_compressor for CSS compression

www.xtreeme.com/javascript-optimizer/ . For JS Compression

32 .Use Cache appropriately

i. Page output caching:

<%@ OutputCache Duration="3600" VaryByParam="none" %>

ii. Page fragment caching:

Write a Page output caching code into each User Control

iii. Data caching:

33) Use server side compression software such as Port80shttp://www.port80software.com/products/httpzip/

34) Usage of "using" and I don't know why it's not yet published.

35) Don't make the member variables public or proteted, try to keep private and use public/protected as properties.

36) Use strString=string.Empty instead of strString="" . [And perhaps instead of strString=null also (?)]

37) Make your page files as light as possible. That is try to avoid unnecessary markups, e.g. use div elements instead of tables.

38) Write static messages in div and make it visible when necessary. This is faster than letting server set Text property of your label or div.

39) Retrieve data from database at once, if possible. Don't add up to database trip as far as possible. For this, combine the datafields from different tables and select them.

40) Use short ID name for WebControl.

Polymorphism

- It allows you to invoke methods of derived class through base class reference during runtime.

- It has the ability for classes to provide different implementations of methods that are called through the same name.

Types of Polymorphism

1. Compile time polymorphism/Overloading/Early Binding

2. Runtime polymorphism/Overriding/Late Binding

- Change the behavior of the method for the derived class

Compile time polymorphism/Overloading/Early Binding

- Performs the different task at the different input parameters.

Runtime polymorphism/Overriding/Late Binding

- Change the behavior of the method for the derived class

- Versioning of a method is called as runtime polymorphism

Key features of OOPs

Encapsulation (Data Hiding)

Encapsulation is process of keeping data and methods together inside objects.

- How to access the class members.

- Who can access the class members

Who can access:

Access Modifiers

Description

Public

No restrictions on accessing public members.

Private

members can be accessed within that class

Protected

members can be accessed within that class and its parent classes. (Private for other classes and public for inherited classes in any assembly)

Internal

members can be accessed within that assembly

internal protected

members can be accessed by that class and its parent class but within that assembly.

How can access:

Modifiers

Description

Const

value of the member cannot be modified

read only

Declare a field that can only be assigned values as part of the declaration or in a constructor in the same class.

Sealed

Specify that a class cannot be inherited.

Static

Access the members using class no need to create object to access that members

Override

Provide a new implementation of a virtual member inherited from a base class.

Virtual

Declare a method or an accessor whose implementation can be changed by an overriding member in a derived class.

Abstract

Can have implmentation of the methods in its child class

Difference between Primary Key and Unique Key

Difference between Primary Key and Unique Key

  • Both Primary Key and Unique Key gives uniqueness of the column on which they are defined.
  • By default Unique Key creates a nonclustered index whereas Primary Key creates a clustered index on the column.
  • A Primary key value cannot be NULL whereas Unique Key allows only one NULL.

Difference between Stored procedure and User Functions

In many situation you can do the same task using either a stored procedure or a function.

Fundamental difference between Stored procedure vs User Functions:

  • Procedure may return none or more values.Function must always return one value either a scalar value or a table.
  • Procedure have input,output parameters.Functions have only input parameters.
  • Stored procedures are called independently by EXEC command whereas Functions are called from within SQL statement.
  • Functions can be called from procedure.Procedures cannot be called from function.
  • Exception can be handled in Procedure by try-catch block but try-catch block cannot be used in a function.(error-handling)
  • Transaction management possible in procedure but not in function.

Difference between Truncate and Delete in SQL

Truncate an Delete both are used to delete data from the table. These both command will only delete data of the specified table, they cannot remove the whole table data structure.Both statements delete the data from the table not the structure of the table.

  • TRUNCATE is a DDL (data definition language) command whereas DELETE is a DML (data manipulation language) command.
  • You can use WHERE clause(conditions) with DELETE but you can't use WHERE clause with TRUNCATE .
  • You cann't rollback data in TRUNCATE but in DELETE you can rollback data.TRUNCATE removes(delete) the record permanently.
  • A trigger doesn’t get fired in case of TRUNCATE whereas Triggers get fired in DELETE command.
  • If tables which are referenced by one or more FOREIGN KEY constraints then TRUNCATE will not work.
  • TRUNCATE resets the Identity counter if there is any identity column present in the table where delete not resets the identity counter.
  • Delete and Truncate both are logged operation.But DELETE is a logged operation on a per row basis and TRUNCATE logs the deallocation of the data pages in which the data exists.
  • TRUNCATE is faster than DELETE.

Wednesday, October 12, 2011

Java Script Trim Function

Its very useful for Trim Function in java script in client and server site.

function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}