Wednesday, August 6, 2014

Shortcut keys for Visual studio 2008,2010,2012,2013

Some of useful Coding Shortcut keys  while developing in Visual Studio..


Collapse Items

Ctrl+M+MCollapse / un-collapse current preset area (e.g. method)
Ctrl+M+H Collpase / hide current selection
Ctrl+M+OCollapse declaration bodies
Ctrl+M+ACollapse all
Ctrl+M+XUncollapse all
Ctrl+m, ctrl+TCollapse Html tag


Edit Code

Ctrl+LDelete current line or selection of lines to and add to clipboard
Ctrl+Shift+LDelete current line or selection of lines
Ctrl+DeleteDelete word to right of cursor
Ctrl+BackspaceDelete word to left of cursor
Ctrl+EnterEnter blank line above cursor
Ctrl+Shift+EnterEnter blank line below cursor
Ctrl+Shift+UMake uppercase
Ctrl+UMake lowercase (reverse upercase)
Ctrl+K+CComment selected text
Ctrl+K+UUncomment selected text
Ctrl+K+\Remove white space and tabs in selection or around current cursor position
Ctrl+K+DFormat document tostyle="width: 10px;" code formatting settings
Ctrl+K+FFormat selection to code formatting settings
Ctrl+Shift+SpaceDisplay parameter required for selected method
Ctrl+Shift+8Visualize whitespace (or press Ctrl+r, then Ctrl+w)
Ctrl+K+DFormat document to code formatting settings
Ctrl+K+FFormat selection to code formatting settings
Ctrl+Shift+TTranspose word to right of cursor; makes b=a out of a=b if cursor was in front of a
Ctrl+TTranspose character left and right of cursor; cursor between ab would make ba
Shift+Alt+TTranspose line: Move line below cursor up and current line down.



IntelliSense and Code Helper

Ctrl+SpaceAutocomplete word from completion list (or alt+right arrow)
Ctrl+Shift+SpaceShow parameter info
Ctrl+F12Display symbol definition
F12Display symbol declaration
Ctrl+JOpen IntelliSense completion list


Build and Debug

F6Build solution (or Ctrl+shift+b)
Ctrl+Alt+F7Rebuild solution
Ctrl+BreakCancel build process
Ctrl+\+EShow error list
F9Toggle breakpoint
Ctrl+BInsert new function breakpoint
F5Start debugging
F11Debug / step into
F10Debug / step over
Shift+F11Debug / step out
Ctrl+F10Debug / run to cursor
Ctrl+Alt+QShow Quickwatch window
Ctrl+Shift+F10Set current statement to be the next executed
Alt+* (on numeric keyboard)Show nexst statement
Ctrl+Alt+EShow Exception dialog box
Ctrl+F11Toggle between disassembly and user code view
Shift+F5Stop Debugging
Ctrl+F5Bypass debugger
Ctrl+Alt+PShow attach to process window
Ctrl+Alt+breakBreak all executing threads


Tool Windows

Ctrl+/Put cursor in the find/command box in toolbar
Ctrl+K+BOpen code snippet manager window
Alt+F11Open macro IDE window
Ctrl+K+WOpen bookmark window
Ctrl+Alt+KOpen call hierarchy window
Ctrl+Shift+COpen class view window
Ctrl+Alt+AOpen Command window
Ctrl+Shift+OOpen Output window
Ctrl+Shift+EOpen Resource view window
Ctrl+Alt+SOpen Server explorer window
Ctrl+Shift+LOpen Solution explorer window
Shift+EscClose Find & Replace Window

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.

Tuesday, July 29, 2014

Difference Between N-tier Architecture and MVC Desgin Pattern

May Several new Learners  Confuses the difference is between MVC (Model View Controller) and N-Tier architectural patterns. It is my intent to clarify the confusion by comparing the two patterns side-by-side. At least in part, I believe the source of some of the confusion is that they both have three distinct layers or nodes in their respective diagrams.


N- Tier Architecture

                                                     
                                                           
- N-tier application architecture provides a model by which developers can create flexible and reusable applications. By segregating an application into tiers, developers acquire the option of modifying or adding a specific layer, instead of reworking the entire application..

Presentation tier

This is the topmost level of the application. The presentation tier displays information related to such services as browsing merchandise, purchasing, and shopping cart contents. It communicates with other tiers by outputting results to the browser/client tier and all other tiers in the network.

Application tier (business logic, logic tier, data access tier, or middle tier)

The logic tier is pulled out from the presentation tier and, as its own layer, it controls an application’s functionality by performing detailed processing.

Data tier

This tier consists of database servers. Here information is stored and retrieved. This tier keeps data neutral and independent from application servers or business logic. Giving data its own tier also improves scalability and performance.

Model–view–controller
                             
                                                             

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.

The Model-View-Controller (MVC) pattern separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes 
Model. The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).
View. The view manages the display of information.
Controller. The controller interprets the mouse and keyboard inputs from the user, informing the model and/or the view to change as appropriate.                                                                                                       
When Do I Choose Which Pattern?

First of all, these two patterns are definitely not mutually exclusive. In fact in my experience they are quite harmonious. Often I use a multi-tiered architecture, such as a three-tiered architecture, for the overall architectural structure.