Quote for the Week

"Learn to enjoy every moment of your life"

Tuesday, August 5, 2014

Generating Random Password in Asp.Net

Sometimes we may required to generate random password to send the user after subscription , for that simply call  a static method as below:

public class static Password
{

publicstatic string CreateRandomPassword(int passwordLength)
{
 string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
 char[] chars = new char[passwordLength];
 Random rd = new Random();

 for (int i = 0; i < passwordLength; i++)
 {
  chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
 }

 return new string(chars);
}
}
call ans

string getPassword=Password.CreateRandomPassword(5); // Gets the Random password.

Do you like this blog posts?
Then Subscribe and Follow this blog to know latest Dot net concepts.
You can also send articles to dotnetcircle@gmail.com

Monday, August 4, 2014

About Triggers in SQL

Triggers
---------

Triggers are the stored sub programs that will automatically invoked based on specified event. Basically these are special type of stored procedure that are automatically fired/executed when a DDL or DML command statement related with the trigger is executed. Triggers are used to assess/evaluate data before or after data modification using DDL and DML statements. 

Types of Triggers
----------------------

Based on Events specified for a trigger, triggers are classified into DDL Triggers and DML Triggers.

 - DDL Triggers are the Triggers that are created by specifying a DDL command as Event.
 - DML Triggers are the Triggers that are created by specifying DML command as Event.

DDL triggers are introduced in SQL Server 2005. In SQL Server we can create triggers on DDL statements (like CREATE, ALTER, and DROP) and certain system defined stored procedures that perform DDL-like operations.

Example : If you are going to execute the CREATE LOGIN statement or the sp_addlogin stored procedure to create login user, then both these can execute/fire a DDL trigger that you can create on CREATE_LOGIN event of Sql Server.
We can use only FOR/AFTER clause in DDL triggers not INSTEAD OF clause means we can make only After Trigger on DDL statements.

DDL trigger can be used to observe and control actions performed on the server, and to audit these operations. DDL triggers can be used to manage administrator tasks such as auditing and regulating database operations.

DML triggers have the following three main purposes:

- Create procedural integrity constraints.
- Record Auditing information of the table.
- Allow insert,update & delete on complex views.

DML triggers are of two types:

1. After Triggers: 
- This Trigger fires after triggering action.  The INSERT,UPDATE,DELETE statements, causes after Inserting,Updating,Deleting Actions.
-  Mainly this are used for Maintaining Inserted, updated, Deleted actions in Audit tables.

Ex:
Table "tblEmployee"

CREATE TRIGGER trig_tblEmployee_Insert/Update/Delete
ON tblEmployee 
FOR INSERT /DELETE
AS 
BEGIN
DECLARE @id int
select @id=Id from inserted // or deleted // inserted and deleted are called Magic Tables, see below for Info,

insert into tblEmployeeAudit(Audit) values("New Employee with Id=cast(@Id as nvarchar(5) is Inserted")// or  Delete query.
END
// A Inserted Information is Added to "tblEmployeeAudit " table in Column "Audit".

Magic Tables:
Related to Triggers there are two table inserted and deleted which were called Magic Tables. This tables are accessible only withiin triggers only. The structure of this tables will be same as currently executing tables within triggers. Main Purpose of this tables is to provide access to new and old values of current row that is INSERTED,UPDATE,DELETED within the Trigger

2. Instead of Triggers.

-  This Triggers will be executed 'Instead of' Executing INSERT,UPDATE,DELETE statements.
-   Main purpose of Instead of Trigger is to allow insert,update,delete on complex views, In Oracle, "Instead of" Triggers can be created only on views, but on SQL Server, "Instead of" Triggers can be on Views as well as Tables.

Example: Create a Trigger on Dept Table on automatically convert Name and Location to Upper Case.

CREATE TRIGGER changecase
on Dept INSTEAD OF  as
BEGIN
Insert Dept select deptId,UPPER(dname),UPPER(location) from inserted

Difference between Triggers and Stored Procedures -

1. Stored procedures must be called by the user only whesreas triggers will be invoked automatically and use cannot invoke manually.
2. Stored procedure can take arguments whereas triggers cannot take arguments because they are automatically invoke.
2. Stored procedure can return a value within ouput parameter. But, trigger cannot return a value either without parameter or return statement




Friday, August 1, 2014

Validating Form using jQuery in .Net

This tutorial will show you how to setup front-end form validation using jQuery in just a few minutes. I’ve kept this tutorial very basic with simple clear instructions so that anyone can implement some validation on their webpage forms. There is a live demo and also a complete download package at the end of the post.

 User Registration Form:


register-form1

Validating Fom

This is what your form will look like when a user tries to submit an empty form.

register-form2

How to Implement :

Step 1: Design your form in HTML

<!-- HTML form for validation demo -->
<form action="" method="post" id="register-form" novalidate="novalidate">

    <h2>User Registration</h2>

    <div id="form-content">
        <fieldset>

            <div class="fieldgroup">
                <label for="firstname">First Name</label>
                <input type="text" name="firstname"/>
            </div>

            <div class="fieldgroup">
                <label for="lastname">Last Name</label>
                <input type="text" name="lastname"/>
            </div>

            <div class="fieldgroup">
                <label for="email">Email</label>
                <input type="text" name="email"/>
            </div>

            <div class="fieldgroup">
                <label for="password">Password</label>
                <input type="password" name="password"/>
            </div>

            <div class="fieldgroup">
                <p class="right">By clicking register you agree to our <a target="_blank" href="/policy">policy</a>.</p>
                <input type="submit" value="Register" class="submit"/>
            </div>

        </fieldset>
    </div>

        <div class="fieldgroup">
            <p>Already registered? <a href="/login">Sign in</a>.</p>
        </div>

</form>


Step 2: Install jquery plugins or we can add reference jquery plugins to View page.

//hosted by Microsoft Ajax CDN
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js">
//hosted by Google API
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
                                             (or)
You can Install jQuery Plugins and Add reference files here

(Ex:
   <script src="jquery.js"></script>
    <script src="jquery.validate.js"></script>     )

<script>


  $(document).ready(function(){
            //form validation rules
            $("#register-form").validate({
                rules: {
                    firstname: "required",
                    lastname: "required",
                    email: {
                        required: true,
                        email: true
                    },
                    password: {
                        required: true,
                        minlength: 5
                    },
                    agree: "required"
                },
                messages: {
                    firstname: "Please enter your firstname",
                    lastname: "Please enter your lastname",
                    password: {
                        required: "Please provide a password",
                        minlength: "Your password must be at least 5 characters long"
                    },
                    email: "Please enter a valid email address",
                    agree: "Please accept our policy"
                },
                submitHandler: function(form) {
                    form.submit();
                }
            });
        }
    }

   

});
</script>

Summary:

 - Do you like this post, want to know more interesting concepts, Just Subscribe to this Blog.

 - Do you have Interesting Concepts like this , then just mail to dotnetcircle@gmail.com to publish in this blog with your name.
 - 

Thursday, July 31, 2014

Understanding SQL Injection in .Net

This article talk about what SQL injection is, how can this effect the security of our websites and what steps should be taken to create an ASP.NET application SQL injection proof.

SQL Injection :

Many databases in today's world are prone to SQL Injection attack. This attack is often used by attackers to attack the database which means it can gain access to database and manipulate the database.

This attack can be more dangerous if account, through which you are accessing the database, has all privileges to access database then attacker can delete the tables or even database itself.

For Example:

When we want to get the data based on username in Asp.net, then writing like:

  String Query = “select * from User_master where User_name ='"+ txtUsername.Text;

Now in textbox txtUsername you pass following value as "'; drop table User_master - -" Now your Query will be like below

 select * from User_master where User_name = ''; drop table User_master - -'

Now what this above code does it executes two statements in first statement it Executes the statement

  select * from User_master where User_name = ''

After that semicolon (;) is there which tells SQL that it is end of first statement then after that it executes the second statement,Syntactically this will two statements, as result, drop table User_master and drops the table.

Note that:- Even if semicolon is not there it will take two as different statements as SQL it self can not identify SQL statement and Parameter you have to tell him which is query and which is parameter.

Solution :

ASP.NET provides us beautiful mechanism for prevention against the SQL injection. There are some thumb rules that should be followed in order to prevent injection attacks on our websites.
User input should never be trusted. It should always be validated: 

- Dynamic SQL should never be created using string concatenations.
- Always prefer using Stored Procedures.
- If dynamic SQL is needed it should be used with parametrized commands.
- All sensitive and confidential information should be stored in encrypted.
- The application should never use/access the DB with Administrator privileges.
- Dynamic SQL should never be created using string concatenations.

If we have dynamic SQL being created using string concatenations then we are always at the risk of getting some SQL that we are not supposed to use with the application. It is advisable to avoid the string concatenations altogether.

Always prefer using Stored Procedures.

Stored procedures are the best way of performing the DB operations. We can always be sure of that no bad SQL is being generated if we are using stored procedures. Let us create a Stored procedure for the database access required for our login page and see what is the right way of doing the database operation using stored procedure.



CREATE PROCEDURE dbo.CheckUser
 (
 @userID varchar(20),
 @password varchar(16)
 )
AS
 select userID from Users where userID = @userID and password = @password
 RETURN

We have to Validate the user with parameterized commands as below code in Asp.net:
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionString))
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "CheckUser";
                cmd.Parameters.Add(new SqlParameter("@userID", username));
                cmd.Parameters.Add(new SqlParameter("@password", password));

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    result = new DataTable();
                    da.Fill(result);

                    //check if any match is found
                    if (result.Rows.Count == 1)
                    {
                        // return true to indicate that userID and password are matched.
                        return true;
                    }
                }
            }
        }

This is a very basic article on SQL injection. I have specifically focused on ASP.NET applications but same concept will apply for any ADO.NET application. This article is meant for the beginner's who know nothing or too little about SQLinjection and making the applications SQL injection proof. I hope this has been informative.


Note: 

- Do you like this Article, do want to  know more Intresting Concepts on .Net, then Subscribe to this Blog.

- Do you have Intresting Articels on .Net, do you want to publish this blog, then mail to 
dotnetcircle@gmail.com to publish in this blog.

Special Thanks to Viewers, Followers as Blog reached 700+ Viewers, 50+ Google plus Followers, 20 + Subscribers


Thanks to each and everyone.