Thursday, May 28, 2009

create an ASPX page that periodically refreshes itself?

The following META tag can be used as a trigger to automatically refresh the page every n seconds:

meta http-equiv="Refresh" content="nn"

This element can be used only within the HEAD element.


Why do uploads fail while using an ASP.NET file upload control to upload large files?

ASP.NET limits the size of file uploads for security purposes. The default size is 4 MB. This can be changed by modifying the maxRequestLength attribute of Machine.config's element.

Should user input data validation occur server-side or client-side? Why?

All user input data validation should occur on the server and minimally on the client-side, though it is a good way to reduce server load and network traffic because we can ensure that only data of the appropriate type is submitted from the form. It is totally insecure. The user can view the code used for validation and create a workaround for it. Secondly, the URL of the page that handles the data is freely visible in the original form page. This will allow unscrupulous users to send data from their own forms to your application. Client-side validation can sometimes be performed where deemed appropriate and feasible to provide a richer, more responsive experience for the user.

System Development Life Cycle (SDLC) Model

This is also known as Classic Life Cycle Model (or) Linear Sequential Model (or) Waterfall Method. This model has the following activities.

1. System/Information Engineering and Modeling

As software is always of a large system (or business), work begins by establishing the requirements for all system elements and then allocating some subset of these requirements to software. This system view is essential when the software must interface with other elements such as hardware, people and other resources. System is the basic and very critical requirement for the existence of software in any entity. So if the system is not in place, the system should be engineered and put in place. In some cases, to extract the maximum output, the system should be re-engineered and spruced up. Once the ideal system is engineered or tuned, the development team studies the software requirement for the system.

2. Software Requirement Analysis

This process is also known as feasibility study. In this phase, the development team visits the customer and studies their system. They investigate the need for possible software automation in the given system. By the end of the feasibility study, the team furnishes a document that holds the different specific recommendations for the candidate system. It also includes the personnel assignments, costs, project schedule, target dates etc.... The requirement gathering process is intensified and focussed specially on software. To understand the nature of the program(s) to be built, the system engineer or "Analyst" must understand the information domain for the software, as well as required function, behavior, performance and interfacing. The essential purpose of this phase is to find the need and to define the problem that needs to be solved .

3. System Analysis and Design

In this phase, the software development process, the software's overall structure and its nuances are defined. In terms of the client/server technology, the number of tiers needed for the package architecture, the database design, the data structure design etc... are all defined in this phase. A software development model is thus created. Analysis and Design are very crucial in the whole development cycle. Any glitch in the design phase could be very expensive to solve in the later stage of the software development. Much care is taken during this phase. The logical system of the product is developed in this phase.

4. Code Generation

The design must be translated into a machine-readable form. The code generation step performs this task. If the design is performed in a detailed manner, code generation can be accomplished without much complication. Programming tools like compilers, interpreters, debuggers etc... are used to generate the code. Different high level programming languages like C, C++, Pascal, Java are used for coding. With respect to the type of application, the right programming language is chosen.

5. Testing

Once the code is generated, the software program testing begins. Different testing methodologies are available to unravel the bugs that were committed during the previous phases. Different testing tools and methodologies are already available. Some companies build their own testing tools that are tailor made for their own development operations.

6. Maintenance

The software will definitely undergo change once it is delivered to the customer. There can be many reasons for this change to occur. Change could happen because of some unexpected input values into the system. In addition, the changes in the system could directly affect the software operations. The software should be developed to accommodate changes that could happen during the post implementation period.

Tuesday, May 26, 2009

How to convert a string to Proper Case?

Use the namespace System.Globalization

string myString = "syncFusion deVeloPer sUppOrt";
// Creates a TextInfo based on the "en-US" culture.
TextInfo TI = new CultureInfo("en-US",false).TextInfo;
Response.Write (TI.ToTitleCase( myString ));

What is the best way to output only time and not Date?

Response.Write(DateTime.Now.ToString("hh:mm:ss"));

Friday, May 22, 2009

Find Visitor's Geographic Location using IP Address in ASP.Net

http://www.aspsnippets.com/post/2009/04/12/Find-Visitors-Geographic-Location-using-IP-Address-in-ASPNet.aspx

How to get IP Address of Visitor's Machine in ASP.Net

http://www.aspsnippets.com/post/2009/04/11/How-to-get-IP-Address-of-Visitors-Machine-in-ASPNet.aspx

How to implement Captcha in ASP.Net

How-to-implement-Captcha-in-ASPNet.aspx

Show Header when GridView is Empty

http://www.aspsnippets.com/post/2009/03/27/Show-Header-when-GridView-is-Empty.aspx

Disable Browser Back Button Functionality using JavaScript

http://www.aspsnippets.com/post/2009/03/24/Disable-Browser-Back-Button-Functionality-using-JavaScript.aspx

Dynamic Date Validation using JavaScript

http://www.aspsnippets.com/post/2009/03/21/Dynamic-Date-Validation-using-JavaScript.aspx

Using JavaScript with ASP.Net GridView Control

http://www.aspsnippets.com/post/2009/03/13/Using-JavaScript-with-ASPNet-GridView-Control.aspx

Scrollable GridView

http://www.aspsnippets.com/post/2009/03/11/Scrollable-GridView-in-ASPNet.aspx

Watermark TextBox using JavaScript

http://www.aspsnippets.com/post/2009/03/06/Watermark-TextBox-using-JavaScript.aspx

Abot Dynamic Controls

http://www.aspsnippets.com/post/2009/03/01/Dynamic-Controls-Made-Easy-ASPNet.aspx

Parameterized Queries

http://www.aspsnippets.com/post/2009/02/09/Parameterized-Queries-ADONet.aspx

TextBox Validation using JavaScript

http://www.aspsnippets.com/post/2009/02/08/TextBox-Validation-using-JavaScript.aspx

Disable Right Click in Browsers

http://www.aspsnippets.com/post/2009/02/07/Disable-Right-Click-in-Browsers.aspx

Check whether username already exists

http://www.aspsnippets.com/post/2009/02/03/Check-whether-username-already-exists.aspx

Display Images from Database using ASP.Net

http://www.aspsnippets.com/post/Display-Images-from-Database-using-ASPNet.aspx

Save and Retrieve Files from SQL Server Database using ASP.Net

http://www.aspsnippets.com/post/2009/02/19/Save-and-Retrieve-Files-from-SQL-Server-Database-using-ASPNet.aspx

Disable pasting and typing of text in FileUpload Control

http://www.aspsnippets.com/post/Disable-pasting-and-typing-of-text-in-FileUpload-Control.aspx

Open PDF File

//Code to Open the PDF File
Pass the Physical Path of the PDF File
e.g: c:/xyz.pdf

private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();
}

Disable Enter key in TextBox to avoid postback in ASP.Net

http://www.aspsnippets.com/post/2009/05/21/Disable-Enter-key-in-TextBox-to-avoid-postback-in-ASPNet.aspx

Export DataSet or DataTable to Word, Excel, PDF and CSV Formats

http://www.aspsnippets.com/post/2009/05/20/Export-DataSet-or-DataTable-to-Word-Excel-PDF-and-CSV-Formats.aspx

For Windows Applications:
http://www.codeproject.com/KB/aspnet/ExportClassLibrary.aspx
for this you need to add dll,which is avaiable in the zip file

List all column names of a table

select column_name from information_schema.columns where table_name='customers'

Enter Text In Into Two TextBoxes At the Same Time


function makesame()
{
document.getElementById('TextBox2').value=document.getElementById('TextBox1').value;
}
//Here makesame() function is called with TextBox1 onkeyup event

asp:TextBox ID="TextBox1" runat="server" onkeyup="makesame()"




if i have 1000 records and i want to access 20 at a time from SQL server, what will be the query?

Use top keyword to fetch the first 20 records from sql server.

for example:
select top 20 * from emp.

you can also use
Set Rowcount keyword to fetch the records from sql server.

ex:
Set Rowcount 20
Select Empname from emp
Set RowCount 0
How to retrieve range of 10th rows to 20 th rows from total rows from a database table.? (Not from Dataset)
select top 10 ID from table1 where ID not in (select top 10 ID from table1)
using row_number() function
 SELECT customerid,customername
FROM (SELECT ROW_NUMBER() OVER (ORDER BY customerid ASC)
AS Row, customerid, customername FROM tbl_customermaster)
AS customermasterWithRowNumbers
WHERE Row >= 10 AND Row <= 20



How to Clear All TextBoxes values without Knowing textbox id(name) ?

Control myForm = Page.FindControl("Form1");
foreach (Control ctl in myForm.Controls)
if (ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
((TextBox)ctl).Text = "";

How do you get records number from 5 to 15 in a dataset of 100 records?

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("trusted_connection=yes;database=northwind;server=localhost");
SqlDataAdapter da = new SqlDataAdapter("select * from customers", con);

DataSet ds = new DataSet();
da.Fill(ds, 4, 11, "cust");
GridView1.DataSource = ds.Tables["cust"];
GridView1.DataBind();

}

Connection Pooling

http://www.codeproject.com/KB/dotnet/ADONET_ConnectionPooling.aspx

Wednesday, May 20, 2009

SQL - Case

SQL - CASE (select)

For this concept, visualize the following table.

employee_nameadmin
Ted0
Terry0
Trish1

As you can see, we have a list of a few employees and then an admin column with boolean (true/false) values for their administration rights (admin). A zero means they are not an admin a 1 mean they are.

Using case logic, we can present this information in a better form.

SQL Code:

SELECT employee_name
CASE admin
WHEN 1 THEN 'yes'
ELSE 'no'
END 'admin'

FROM employees;


employee_nameadmin
Tedno
Terryno
Trishyes

In short all we really did is replace 1's and 0's with the words 'yes' and 'no'.


SQL - Case (update)

Case functions additionally allow for the updating of records within your table. For example, we could update the prices of items in our online store, but more importantly we could update very specific records because of the conditional logic allowed by case.

Let's use the following table for this next example.

itemquantityprice
goldfish121.00
guppy240.50
blow fish15.00

Let's say we wanted to have a sale to clean out some of our overstock. We'll go ahead and take 25% off of all our items that we currently have 20 or more of (>20). Then we'll take 10% off the items that we have 10-20 of (between 10 and 20) and everything else we will discount only 5%.

SQL Code:

UPDATE inventory SET price = price *
CASE
WHEN quantity > 20 THEN 0.75
WHEN quantity BETWEEN 10 AND 20 THEN 0.90
ELSE 0.95
END;


itemquantityprice
goldfish12.9
guppy240.375
blow fish14.75

Each price has automatically been reduced by the appropriate percentages.

GROUP BY Function

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

SELECT column_name, aggregate_function(column_name) FROM table_name
WHERE column_name operator value GROUP BY column_name

Id Name Mark

1 Anu 71
2 Athira 60
3 Faizal 67
4 Anu 69
5 Faizal 49

select Name,sum(Mark) from Student Group By Name

Anu 140
Athira 60
Faizal 116

If you omit Group By then

select Name,sum(Mark) from Student Group By Name ----> will result

Anu 316
Athira 316
Faizal 316
Anu 316
Faizal 316

Inserting single quotes to a string in sql query

Just Add one more single quotes to that string by the user

eg: insert into table name values('De''zousa')

or

The programmer has to maintain that one using coding
Means we have to check the string if a single quotes exists or not.
If exists we have to add one more single quotes to that string.

Tuesday, May 19, 2009

Copying Data between tables

To import data from one (or) more tables into another table,T-SQL provides two statements:
  • select..........into
  • insert.....into....select
select....into
This statement creates destination table structure automatically without constraints and copies rows from one (or) more source tables
Tables may be temporary tables (or) permanent tables.

syntax: select */columnnames into destinationtable from sourcetable

Monday, May 11, 2009

SQL QUERIES

TO GET THE PART OF DATETIME
  • DATEPART(DATEPORTION,ANYDATE)    => O/P:NUMERIC OUTPUT
  • DATENAME(DATEPORTION,ANYDATE)   =>O/P:STRING OUTPUT
EXAMPLES:
=>DISPLAY ONLY MONTH VALUE OF CURRENT DATETIME
          select datepart(mm,getdate())   o/p:5
=>DISPLAY MONTH NAME OF CURRENT DATETIME
          select datename(mm,getdate())  o/p:may
=>DISPLAY WEEKDAY OF CURRENT DATE
         select datename(dw,getdate())      o/p:monday

Thursday, May 7, 2009

Working with OverRiding

  • OverRiding is a concept of having two methods with same name and same args in base and derived classes.
  • In OverRiding,by default importance will be given to local methods.
  • "base" is a Keyword.
  • "base" points to parent class.
  • "this" points to current class.
  • In OverRiding,in order to access parent class methods,base.methodname() need to be used
  • "base" keyword can be used with methods,fields and constructors also
Example on "base" keyword with methods.

              class A
        {
            public void Show()
            {
                MessageBox.Show("From A....");

            }
        }
        class B : A
        {
            public void Show()
            {
                MessageBox.Show("From B....");
                base.Show();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            B obj = new B();
            obj.Show();
        }

Using DialogResult

DialogResult dr = MessageBox.Show("Are you getting Bonus", "Dialogresultdemo",                                                                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Question);

if (dr == DialogResult.Yes)
  {
       ur coding.....
   }

else
{
   ur coding......
}

Program to OpenCalculator

using System.Diagnostics;//namespace

 private void button1_Click(object sender, EventArgs e)
        {
            Process.Start("calc.exe");
        }

Monday, May 4, 2009

Improving ADO.NET performance

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

Alphabetical Paging in Gridview

using System.Data.SqlClient;

public partial class alpahbetical_paging : System.Web.UI.Page
{
    string query;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            query = "select * from customers";
            FillGrid(query);
        }
    }

    private void FillGrid(string s)
    {
        SqlConnection con = new SqlConnection("trusted_connection=yes;database=northwind;server=localhost");
        SqlDataAdapter da = new SqlDataAdapter(query, con);
        DataSet ds = new DataSet();
        da.Fill(ds, "Customers");
        GridView1.DataSource = ds.Tables["Customers"];
        GridView1.DataBind();
    }

//The RowCreated event is used to create the list.

// In the event first  check for the footer row.

// Once, the footer row is found  run a loop from 65 to 92 and convert each number into the character representation.

// The number 65 stands for “A”, 66 for “B” and so on till 92 for “Z”. Inside the loop  create a LinkButton and set the Text property to the alphabet. Finally, the control is added to the cell collection.

//Creating the Alphabetical List:

//The next task is to create an alphabetical list and display it in the GridView control.

//The best place to display the list is the GridView footer.



    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            TableCell cell = e.Row.Cells[0];
            cell.ColumnSpan = 5;
            for (int i = 65; i <= (65 + 25); i++)
            {
                LinkButton lb = new LinkButton();
                lb.Text = Char.ConvertFromUtf32(i) + "";
                lb.CommandArgument = Char.ConvertFromUtf32(i);
                lb.CommandName = "AlphaPaging";
                cell.Controls.Add(lb);
            }
        }
    }

//Fetching the Records Based on the Alphabet:

//In the last section we created the alphabets and displayed them in the footer of the GridView control.

//The next task is to capture the event generated by the alphabets when we click on them and fetch the results based on the alphabet. The RowCommand event is fired whenever you click on any alphabet.



    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if(e.CommandName.Equals("AlphaPaging"))
        {
            query = "select * from customers where contactname LIKE '" + e.CommandArgument + "%'";
            FillGrid(query);
        }
    }

Gridview Sorting

protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
FillGrid("CustomerID");
}
}

private void FillGrid(string col_name)
{
SqlConnection con = new SqlConnection("trusted_connection=yes;database=northwind;server=localhost");
SqlDataAdapter da = new SqlDataAdapter("select * from customers order by " + col_name, con);
DataSet ds = new DataSet();
da.Fill(ds, "customers");
//Sorted info is placed into Dataset ds.
GridView1.DataSource = ds.Tables["customers"];
GridView1.DataBind();
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
FillGrid(e.SortExpression);
//e.SortExpression will provide column selected by user.
}

Gridview Paging

protected void Page_Load(object sender, EventArgs e)
{
//First page records to be downloaded for ordinary request.
if (Page.IsPostBack == false)
{
GridView1.PageIndex = 0;
FillGrid();
//DataBind method of gridview will perform paging.It will send page records to user based up on
//pageindex property value
Label1.Text = "1 out of" + GridView1.PageCount;
}
}

private void FillGrid()
{
SqlConnection con = new SqlConnection("trusted_connection=yes;database=northwind;server=localhost");
SqlDataAdapter da = new SqlDataAdapter("select * from customers", con);
DataSet ds = new DataSet();
da.Fill(ds, "Customers");
GridView1.DataSource = ds.Tables["Customers"];
GridView1.DataBind();
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
//e.NewPageIndex will provide page number to be downloaded to client.
FillGrid();
Label1.Text = e.NewPageIndex + 1 + " Out of " + GridView1.PageCount;
}