Thursday, 30 January 2014

What is the difference between declare variable inside or outside the loop in C# ASP.NET

Sometimes user Search these type of questions :-
  • Difference between declaring variables before or in loop
  • Is it better to declare a variable inside a loop
  • Is there is any performance difference between declare a variable outside or inside a loop 
Solution:-

In Short, Performance-wise both cases are compiled to the same IL, so there's no difference.

Let's See Example
Case 1: 
                int num;
                for (int i = 0; i < count; i++) 
                {
                        num = i;
                }


Case 2:
for (int i = 0; i < count; i++) { int num = i; }
 I think only difference between above two cases is, defining variables inside the loop makes it visibility local to that loop only because declaration does not cause any perceivable difference in performance.Personally, I Prefer the second one because it reduces scope of variables to where they are needed, which is good thing. 


That’s it!!…..Happy Programming...

Friday, 24 January 2014

How to avoid the cache of Textbox in C# ASP.NET

Sometimes user want to disable history from the text box. Suppose when user enter information like credit card number and again if user enter another number then no previous value should be available in the text box's history.
Here 5,8 are those numbers which were entered by user for this textbox, this clearly shows textbox is caching history.
I am going to disclose two ways to solve this problem which are shown below:-

1. By Using Asp.Net Property :
 
<asp:TextBox ID="txtNumber" runat="server" AutoCompleteType="Disabled"></asp:TextBox>

2. By Using JavaScript Code :
<asp:TextBox ID="txtSearch" runat="server" onfocus="disableautocomplete(this.id);" ></asp:TextBox>
JavaScript Function
function disableautocomplete(id) {
            var passwordControl = document.getElementById(id);
            passwordControl.setAttribute("autocomplete", "off");
        }

I think, best option would be to write a JavaScript function rather than just using 'AutoCompleteType' Property bcoz it ensures working in all browsers rather than just major browsers.


That’s it!!…..Happy Programming...

Tuesday, 14 January 2014

Allow only Numeric Value in textbox in C# ASP.NET using JAVASCRIPT

Some times a user search these types of questions :-

  • Allowing only certain character in a text box.
  • Validation in TextBox which accepts only numbers value.
  • Allow only numbers / digits in TextBox.
  • Prevent user to enter manual text in TextBox.

I am Going to implement a function which will answer all of these questions.
<script type="text/javascript">
    function allowOnlyNumeric()
    {
        if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8)
        {
            return false;
        }
    }
</script> 


If you want to prevent user to enter any other value except numeric, just do like this
 
<asp:TextBox ID="txtNumber" runat="server" onkeypress="return allowOnlyNumeric()"></asp:TextBox>


If you want to prevent user to enter any manual text, just do like this
<asp:TextBox ID="txtNumber" runat="server" onkeypress="return false;"></asp:TextBox>

That’s it!!…..Happy Programming...






Saturday, 11 January 2014

How to Insert Values into an Identity Column in SQL Server

Identity field is generally used as a primary key. When we insert a new record into our table, this field automatically assign an incremented value from the previous entered value in it. Generally, we can't insert our own value in this field.

In this article, I am going to display the tips for inserting our own value in this field. Let us assume the following Student table.
CREATE TABLE Student
(
 ID int IDENTITY,
 Name varchar(100),
 Class varchar(50)
) 
Now, I am trying to insert a record into Student table with identity field like this then I will get the error message as shown below.
INSERT INTO Student(ID,Name,Class) VALUES(1,'Jassi','fifth')

We can alllow insert to the identity field by setting IDENTITY_INSERT ON for a particular table as shown below:

SET IDENTITY_INSERT Student ON
Now, lets see how to insert our own values to identity field ID in Student table. 
INSERT INTO Student(ID,Name,Class) VALUES(1,'Jassi','fifth')
INSERT INTO Student(ID,Name,Class) VALUES(2,'Sonu','Seventh')
Now, lets see output of Student table.
After Inserting your own value to identity make sure you set IDENTITY_INSERT OFF.
Reset the Identity field
DBCC checkident (Student, RESEED, 1)
Now if we insert any new row in Student table its value start from 2.


That’s it!!…..Happy Programming...

Sunday, 5 January 2014

What is a SQL Injection Attack and how can avoid from it in C# ASP.NET

A SQL Injection attack is a form of attack that comes from user input that has not been checked to see that it is valid. The objective is to fool the database system into running malicious code that will reveal sensitive information or otherwise compromise the server.

aspx page

<form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtsearch" runat="server"></asp:TextBox>
            <asp:Button ID="btnSearch" runat="server"
                OnClick="btnSearch_Click" Text="Search" />
        </div>
        <asp:GridView ID="grdRecords" runat="server"
            CellPadding="4" ForeColor="#333333"
            GridLines="None" Height="150px"
            OnSelectedIndexChanged="grdRecords_SelectedIndexChanged"
            Width="350px">
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333"
                HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
            <HeaderStyle BackColor="MediumPurple" Font-Bold="True" ForeColor="White" />
        </asp:GridView>
</form>


aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void showData(String strssearch)
    {
        String strcon = WebConfigurationManager.ConnectionStrings["dbMasterConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strcon);
        String tsql = "select * from ContactUs where name = '" + strssearch + "'";
        SqlCommand cmd = new SqlCommand(tsql, con);
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        grdRecords.DataSource = reader;
        grdRecords.DataBind();
        reader.Close();
        con.Close();
    }

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

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        showData(txtsearch.Text);
    }
}

Create Sql Table and Insert some records in it


Create table ContactUs
(
name nvarchar(50) not null,
email nvarchar(128) not null,
msgSubject nvarchar(50) not null,
msgComment nvarchar(100) not null
)
And when we run the application, it would show you something like this :

But when we run this application with the following text :-  "a 'OR' 0 '=' 0"  this is a part of sql injection.It would show something like this :


Prevent from Sql Injection Attacks :-


Never trust user input - Validate all textbox entries using validation controls, regular expressions, code, and so on
Never use dynamic SQL - Use parameterized SQL or stored procedures
Never connect to a database using an admin-level account - Use a limited access account to connect to the database
Don't store secrets in plain text - Encrypt or hash passwords and other sensitive data; you should also encrypt connection strings
Exceptions should give minimal information - Don't reveal too much information in error messages; use customErrors to display minimal information in the event of unhandled error; set debug to false


That’s it!!…..Happy Programming...

Saturday, 4 January 2014

How to Show Date & Time Difference in Days, Hours, Minutes and Seconds in C# ASP.NET

First Create a Class and Code like this :-

using System;
using System.Web;

public static class ActualTime
{
    public static string TimeAgo(DateTime date)
    {
        DateTime currentDate = DateTime.Now;//To get current date
        TimeSpan actualTime = currentDate.Subtract(date);   
     
        if (actualTime.TotalMilliseconds < 1)
            return "not yet";
        if (actualTime.TotalMinutes < 1)
            return "just now";
        if (actualTime.TotalMinutes < 2)
            return "1 minute ago";
        if (actualTime.TotalMinutes < 60)
            return string.Format("{0} minutes ago", actualTime.Minutes);
        if (actualTime.TotalMinutes < 120)
            return "1 hour ago";
        if (actualTime.TotalHours < 24)
            return string.Format("{0} hours ago", actualTime.Hours);
        if (actualTime.TotalDays == 1)
            return "yesterday";
        if (actualTime.TotalDays < 7)
            return string.Format("{0} days ago", actualTime.Days);
        if (actualTime.TotalDays < 14)
            return "last week";
        if (actualTime.TotalDays < 21)
            return "2 weeks ago";
        if (actualTime.TotalDays < 28)
            return "3 weeks ago";
        if (actualTime.TotalDays < 60)
            return "last month";
        if (actualTime.TotalDays < 365)
            return string.Format("{0} months ago", Math.Round(actualTime.TotalDays / 30));
        if (actualTime.TotalDays < 730)
            return "last year";
        else
        {
            return string.Format("{0} years ago", Math.Round(actualTime.TotalDays / 365));
        }
    }
}
This class will return the output in string but we must pass parameter value in it to get the result


aspx page
Take One label and One textbox like this :

  <asp:TextBox ID="txtDate" runat="server" OnTextChanged="txtDate_TextChanged" AutoPostBack="true"></asp:TextBox>

    <asp:Label ID="lblDate" runat="server" Text="Actual time will show here"></asp:Label>

aspx.cs page
protected void txtDate_TextChanged(object sender, EventArgs e)
    {
        DateTime userInputDate = Convert.ToDateTime(txtDate.Text);
        lblDate.Text = ActualTime.TimeAgo(userInputDate);
    }


Output



That’s it!!…..Happy Programming...