Tuesday, March 21, 2017

Non-WWW to WWW with HTTP to HTTPS


Today we will discuss how to redirect non www to www.domain.com with http to https both at time. few days back while moving a domain from http to https as now google chrome 56 is marking the website with http as non-secure and it’s also mentioned by google that it’s just a warning and near future it will be fully implemented so i suggest you people also to move your domain to https. there are many benefits of https we are not going to discuss here so let's come to the point.
we will discuss the web.config rule to resolve the problem. i implemented https perfectly and on my website all URL mentioned below are working fine:

http://domain.com
    https://domain.com
    http://www.domain.com
    https://www.domain.com

but the problem was that google consider every URL different and in SEO it is not a good practice. so I want something like below:
http://domain.com => https://www.domain.com
    https://domain.com => https://www.domain.com
    http://www.domain.com => https://www.domain.com
    https://www.domain.com => https://www.domain.com

so all URL should be resolved to same URL so it will not make problem in SEO and also good for alexa ranking. In Asp.Net we can do this by URL Redirecting rules in your web.config. for URL Redirecting more information please check here Let's have a look on code how it will be done by using web.config URL Redirect rewrite rules.
In web.config section you can put these rule like below:


<rewrite>
      <rules>
        <clear />
        <rule name="Redirect to https" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
        </rule>
    </rewrite>

First i make this rule and it was working perfect for redirecting http to https for all url on my domain.

http://domain.com => https://www.domain.com working ok
http://www.domain.com => https://www.domain.com working ok
https://www.domain.com => https://www.domain.com working ok

but there was a problem with https non www url.
https://domain.com => https://www.domain.com not working with above URL Redirect rule. after that i tries to change the

From: <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
    TO: <action type="Redirect" url="https://www.{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />

but there was no change so after searching and too much R&D i came back to my old url redirect rule which was before working fine from simple http to www http and i try that rule again. give below:

<rule name="Redirects to www" patternSyntax="ECMAScript" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAny">
                <add input="{HTTP_HOST}" pattern="^domain.com$" />
            </conditions>
            <action type="Redirect" url="https://www.domain.com/{R:0}" />
        </rule>

so I came to a result that with a single rule it’s not possible to resolve both problems, from http to https and from non www to www.
Above mentioned both rules we have to put in same web.config file and it's working fine for both issues.
here is the full version of both rules:

<system.webServer>
    <rewrite>
      <rules>
        <clear />
        <rule name="Redirect to https" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
        </rule>
        <rule name="Redirects to www.domain.com" patternSyntax="ECMAScript" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAny">
                <add input="{HTTP_HOST}" pattern="^domain.com$" />
            </conditions>
            <action type="Redirect" url="https://www.domain.com/{R:0}" />
        </rule></rules>
</rewrite>
</system.webServer>


Note: its not final, i am still working on this if you people can comment/suggest some good thing better than this so please share it will be appreciable.
Comments and Suggestion are always welcome!

Monday, March 20, 2017

Validation Controls in Asp Net


Today we will discuss Validation Controls in Asp.Net and we will have a deep look on Custom Validator control in Asp.net.
Validation is a most important process either it is a web based application, desktop application or some other like android or iPhone. without proper validation, it is very difficult for a system to survive because we don't know the nature of client/audience so as per our requirements we will must have to check the input from user and then process it.
Asp.Net provides very powerful controls for validation. In Asp.Net we have basically six validation control which can be used as per the requirements. we can validate the useless or contradictory data input from user. if something is going to harm the system we can validate and stop the user request with proper message or user friendly alert.
Asp.Net gives following validation controls:
  • RequiredFieldValidator
  • RangeValidator
  • CompareValidator
  • RegularExpressionValidator
  • CustomValidator
  • ValidationSummary

What is BaseValidator Class: All validation control performs some operation according to their nature and these control have their built-in classes, these control classes are inherited from a base class that's called BaseValidator class, which give some common properties and method to all validation controls. you can check in below image:


Now we will check validation control in details.

1. RequiredFieldValidator Control:
RequiredFieldValidator is generally used with input text field to check whether the input field is empty or have some text and it will validate that input text field should must have some text not empty.
Example/use of RequiredFieldValidator:

<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvcUserName" runat="server" ControlToValidate ="txtUserName" ErrorMessage="Please enter Username"></asp:RequiredFieldValidator>


In above example, we can check how we will use RequiredFieldValidator with a Asp.Net TextBox.
2. RangeValidator Control:
On mostly website we have seen it asks for password should be minimum 6 and maximum 20 in length. if we enter less than 6 or greater than 20 it will never let us proceed further. RangeValidator control is used to check whether input from the user falls between this range or no.
RangeValidator has three specific properties:
Type: It check the type of input from the user. The available values are: Date, Double, Currency, Integer, and String.
MinimumValue specifies minimum value of the range.
MaximumValue specifies maximum value of the range.
Syntax/Example of RangeValidator control is as:

<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
        <asp:RangeValidator ID="rvPasswords" runat="server" ControlToValidate="txtPassword" ErrorMessage="Enter your password between 6 - 12 (only number)" MaximumValue="12" MinimumValue="6" Type="Integer"></asp:RangeValidator>


In above example, we create a password textbox field and in RangeValidator we have set the properties like user can only enter length between 6 to 12 because MinimumValue will check that input should not be less than 6 and MaximumValue will verify input should not b greater than 12, we have set Type is Integer so user can only enter Integers otherwise RangeValidtor will not pass the validation.

3. CompareValidator Control:
When we are submitting a registration form to create a user profile then mostly it requires to set Password for your account, always there are two password fields with label Password and Confirm Password. whatever password we set for the account we have to match the Password and Confirm Password fields. how this confirm password verifies the user input is same that could be done in Asp.Net by using CompareValidator control. we can perform this operation by many other ways and also, we can use CompareValidator control for many other purposes but it was most general and used example for this control.
however, let's have a look on some specific properties of this control:
Type: specifies the data type.
ControlToCompare check the value of the input control to compare with.
ValueToCompare verifies constant value to compare with.
Operator it provides comparison operator, the available values are: GreaterThan, GreaterThanEqual, LessThan, Equal, NotEqual, LessThanEqual, and DataTypeCheck.
Syntax/Example of this control is:

<asp:TextBox id="TextBox1" runat="server"/><br />
        <asp:TextBox id="TextBox2" runat="server"/>
        <asp:CompareValidator id="Compare1" ControlToValidate="TextBox1" ControlToCompare="TextBox2" Type="String" Text="Value does not match" runat="server"/>


In above example, we have two Textboxes and we are comparing their values with each other. if user input is different in both textboxes then it will not pass validation and show the error message "Value does not match".

4. RegularExpressionValidator Control:
RegularExpressionValidator is used when we want our input to be verified with a specific pattern,it may be some phone number format,currency.etc,or we want our input should only contain alphabets not numbers.basically we use a regular expression to match the input which can be done by using RegularExpressionValidator control. we set a regular expression in this control and tell the validator control name of input field then it verifies that input field should validate the expression.
Let's have a look on simple example:

<asp:TextBox ID="txtName" runat="server"/>
    <asp:RegularExpressionValidator ID="regexpName" runat="server" ErrorMessage="This expression does not validate." ControlToValidate="txtName" ValidationExpression="^[a-zA-Z']$" />


5. CustomValidator Control:
Sometime we do not require above all control to check our input and we want to perform some other operation on the user input. so, for such purpose we can use customValidator control. we can perform client side operation and server side also by using this customer control validator. for check input at client side we can use ClientValidationFunction property and for server we can use ServerValidate event handler. client routine can be built by using any script language like Javascript or VBScript or any other understand by browser and in server side we can use any Asp.Net language like C# or VB.Net.
Syntax/Example for the control is:

<asp:TextBox id="Text1" runat="server" />
    <asp:CustomValidator id="CustomValidator1" ControlToValidate="Text1" ClientValidationFunction="ClientValidateFunction" OnServerValidate="ServerValidationFunc" ErrorMessage="Not an even number!" runat="server"/>


In above example, we can see we set the client side and server side routines to perform the operation.
6. ValidationSummary Control:
ValidationSummary is basically used to summarize the error messages from all validation control on the page. it shows the error messages per the DisplayMode property. it collects all validation control error message from a common property "ErrorMessage" of each control. if we skip the ErrorMessage property of any validation control then it will not show error message for that control. there are different properties to present error messages nicely on page by using ValidationSummary Control.
Syntax/Example Lets understand with an example:

<asp:TextBox ID="TextBox2" runat="server" />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox2" ErrorMessage="Enter Card Type" Text="*" runat="server"/>
            <asp:TextBox ID="TextBox1" runat="server" />
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="TextBox1" ErrorMessage="Enter Card Number" Text="*" runat=server/>
            <asp:ValidationSummary id="valSum" DisplayMode="BulletList" EnableClientScript="true" HeaderText="You must enter a value in the following fields:" runat="server"/>


In above example validationsummary will show error message, in bullets, from the both required field validator control with a header text.
Comments and Suggestions are always welcome

Difference between document.ready and window onload

Today we are going to look at the difference between document.ready and window.onload events.
In JavaScript we use window.onload() whereas in JQuery we are using $(document).ready() and normally developer think these both are same but it’s not true because there are many differences between them. Basically JQuery wrap up the window.onload() from JavaScript and give the world $(document).ready() but still both are different.
Let's have a look with example:

Window.onload():
This method called up when all data/content on a page is fully loaded here all content means DOM, images, async scripts etc all we have on a page. onload method must wait for images and other frames to load and after that this event is fired.

$(window).load(function () {
             alert("all content is loaded");
    });


By adding these lines to any page, it will show alert when page is fully loaded.There is another way to call this event is:

<body onload="func_call();" >


we can add this to the body tag of page and it will work same like $(window).onload.

$(document).ready():
JQuery execute earlier than window.onload. document.ready event is fired when all DOM is loaded on the page. DOM (document Object Model) include all html tag and scripts it does not include the images and other frames. DOM load is early stage of a page to load that’s why this event starts earlier than window.onload(). so when DOM is ready document.ready() event will start execution.

$(document).ready(function () {
              alert("DOM is ready.");
    });


Another way which work same like document.ready or we can say shorthand for document.ready is:

$(function() {
        alert("DOM is ready." );
    });


Notes:
  1. Window.onload is a JavaScript event and document.ready is specific event from JQuery.
  2. If you have to perform some manipulation on images then its preferred to use window.load but if your operations are only related to DOM then use document.ready.
  3. On a single page we cannot use window.load event more than one whereas document.ready is allowed to use more than once. we can have multiple document.ready but window.load will be single on a page.

Comment and suggestion are always welcome.

Thursday, March 16, 2017

Order by clause with Union in Sql Server

Problem: use of order by with union statement.
We will discuss different ways of using order by statement with union statement.
mostly developer tries to add order by in both union statements like below:

SELECT COLUMN1,COLUMN2 FROM TABLE1
    ORDER BY COLUMN1
    UNION ALL
    SELECT COLUMN1,COLUMN2 FROM TABLE2
    ORDER BY COLUMN1

This query is not correct and it will throw an error:
incorrect syntax near order by.
SQL union does not support two order by statement as union is used to combine two queries result as one so how is it possible to have two order by statements for one result set.
However, there are other ways to order both query as per requirements but not with two order by statements. Let's have a look first on simple syntax that how we can use order by with union statement.

SELECT COLUMN1,COLUMN2 FROM TABLE1 
    UNION ALL
    SELECT COLUMN1,COLUMN2 FROM TABLE2 
    ORDER BY COLUMN1




This query will order the union result per Column1 value. this is the most simple and cleaner statement we can use for order by with union statement.
Now another scenario if you have some complex query and it’s difficult for you to handle the order by as mentioned in above query then you can use below query it will give you little more control over the query and you can perform some more operation.

SELECT * FROM (
    SELECT COLUMN1,COLUMN2 FROM TABLE1 
    UNION ALL
    SELECT COLUMN1,COLUMN2 FROM TABLE2 
    )R
    ORDER BY R.COLUMN1,R.COLUMN2,GETDATE()




I share above query because I face on issue on simple order by with union statement so I resolved with this query. maybe you require the union result be joined with some other table so it will be easy for you to handle with this query. however, it is not as much cleaner and its using also subquery so may be some performance factor affect your results.
Now if you want to order you both queries should be order by independently from each other than you can use below query. for example, you want first and second query of union should be sorted differently/independently then have a look:

SELECT COLUMN1,COLUMN2,CREATED_DATE,'1' as orderbyKey FROM TABLE1
    UNION ALL
    SELECT COLUMN1,COLUMN2,CREATED_DATE,'2' as orderbyKey FROM TABLE2 
    ORDER BY orderbyKey




This query will show first record of top query and then bottom query records accordingly.
If we want to sort the result set that it first shows the top query result and then bottom query result and these should be order by Created Date descending then we can do this below:

SELECT COLUMN1,COLUMN2,CREATED_DATE,'1' AS ORDERBYKEY FROM TABLE1 
    UNION ALL
    SELECT COLUMN1,COLUMN2,CREATED_DATE,'2' AS ORDERBYKEY FROM TABLE2 
    ORDER BY ORDERBYKEY ASC,CREATED_DATE DESC 




Complete Script:

USE tempdb
GO
-- Create table
CREATE TABLE TABLE1 (COLUMN1 INT, COLUMN2 VARCHAR(50),CREATED_DATE DATETIME);
CREATE TABLE TABLE2 (COLUMN1 INT, COLUMN2 VARCHAR(50),CREATED_DATE DATETIME);
GO
--INSERT Sample Data 
INSERT INTO TABLE1 (COLUMN1, COLUMN2,CREATED_DATE)
SELECT 1, 'VAL1_TABLE1',GETDATE()
UNION ALL
SELECT 2, 'VAL2_TABLE1',GETDATE()+1
UNION ALL
SELECT 3, 'VAL3_TABLE1',GETDATE()+2;
INSERT INTO TABLE2 (COLUMN1, COLUMN2,CREATED_DATE)
SELECT 3, 'VAL1_TABLE2',GETDATE()
UNION ALL
SELECT 2, 'VAL2_TABLE2',GETDATE()+3
UNION ALL
SELECT 1, 'VAL3_TABLE2',GETDATE()+5;
GO

 --1ST
 SELECT COLUMN1,COLUMN2 FROM TABLE1
 ORDER BY COLUMN1
 UNION ALL
 SELECT COLUMN1,COLUMN2 FROM TABLE2
 ORDER BY COLUMN1
 go
 --2ND
 SELECT COLUMN1,COLUMN2 FROM TABLE1 
 UNION ALL
 SELECT COLUMN1,COLUMN2 FROM TABLE2
 ORDER BY COLUMN1
 go
 --3RD 
 SELECT * FROM
 SELECT COLUMN1,COLUMN2 FROM TABLE1
 UNION ALL
 SELECT COLUMN1,COLUMN2 FROM TABLE2
 )R
 ORDER BY R.COLUMN1,R.COLUMN2,GETDATE()
 go
 --4TH
 SELECT COLUMN1,COLUMN2,CREATED_DATE,'1' as orderbyKey FROM TABLE1
 UNION ALL
 SELECT COLUMN1,COLUMN2,CREATED_DATE,'2' as orderbyKey FROM TABLE2 
 ORDER BY orderbyKey
 go
 --5TH<
 SELECT COLUMN1,COLUMN2,CREATED_DATE,'1' AS ORDERBYKEY FROM TABLE1 
 UNION ALL
 SELECT COLUMN1,COLUMN2,CREATED_DATE,'2' AS ORDERBYKEY FROM TABLE2 
 ORDER BY ORDERBYKEY ASC,CREATED_DATE DESC 
go
-- Clean up
DROP TABLE TABLE1;
DROP TABLE TABLE2;
GO

Comments and suggestions are always welcome!

Wednesday, March 15, 2017

What is HTTP Protocol

HTTP: HTTP stands for Hypertext Transfer Protocol. HTTP is base for WWW (World Wide Web => internet) to communicate data between client and server. HTTP is stateless protocol that is used by its request methods, status like error code and headers of request or response. In this post, we will discuss HTTP for computer students and for developers. Let’s have a look on few parts of HTTP. There are mainly three features of HTTP.

First: Connection-less, HTTP is a connectionless. what happens when we make request to server for some data or images. so, it makes connection from client to server and get response also that is also a connection from server to client. In fact, the scenario is that when a client browser send request to server after sending request it discontinue the connection and wait for server, at the other hand server receive request and complete process and then make again connection to client and send back the response to client.

Second: Media independent, by using HTTP we can send any type of data but our client and server, both should know the content type and understand that how they will handle the data. there is no restriction just we must pass content type by using correct MIME-TYPE so it become easy to handle for the server.

Third: Stateless, HTTP is connectionless and stateless because client and server don't know each other after the request is completed. server and client know each other only when they are communicating with each other after completion connection is finished and client and server become unknown to each other. 

In HTTP/1.0 for each new request/response between server and client they create a new connection, but in HTTP/1.1 have the capability to make one or more request/response.
When we use term HTTP protocol then it means request/response based to the client/server architecture. as shown in below picture that web browser or search engines behave like a HTTP client and Web Server becomes servers.


What is Client: An HTTP client may be a browser or search engine or robot, is used to send request to server in the form of method, any protocol version or using URI which is attached with a specific MIME-TYPE which tell the server it contains a client information, a modifier and may a having content in the body of request.

What is Server: HTTP server who process the client request and send response to client. This response may have any protocol version or maybe it gives response in error code like status code 404 Not found, 401 Unauthorized, a response has some MIME-TYPE and may be the response data in body content. 

HTTP Versions: HTTP basically used HTTP/. version scheme. now updated is HTTP/2 actually HTTP/2.0. Example:

HTTP/1.0 or HTTP/1.1 or HTTP/2.0

What is URI: URI stands for Uniform Resource Identifier. it is used to represent any website or WebApi and it have all basic info of the resource like location, name etc.
Syntax for URI:
URI = "http:" "//" HTTP_HOST/HTTPS [ ":" port ] [ abs_path [ "?" query string ]]

Let have a look on below example for understanding:
1. http://abc.com:80/~jdoe/finaltext.html
2. http://ABC.com/%7Ejdoe/finaltext.html
3. http://ABC.com:/%7ejdoe/finaltext.html

These all above mentioned URI are same/equivalent. why? because as we know 80 is default port so it does not matter either its written or not, ~ notation HEX is %7E so either we enter the ~ or %7E it will be same and browser will convert this to HEX and understand automatically and also there is no restriction for case sensitive.

HTTP Request Methods:
1. GET: it is used to get some data or retrieve any information from the server. The basic purpose for what it is used for getting something from the server only.
2. HEAD: it’s used is same like GET but it is basically for header section information and give the status of request.
3. POST: mostly POST is used to send data or record to server for processing either insert into data or some other operation like file upload etc.
4. PUT: used to update the data or file or records, its function is to replace the current data with newly uploaded.
5. DELETE: as the name show it will remove all record on target server by the provided URI.
6. CONNECT: is used for tunneling between client and server. it will create a tunnel to server indicated from the URI.
7. OPTIONS: it is used to check the communication is allowed between the client and server.
8. TRACE: is used to send a response back to test with the path to the target resource.
In this post, we try to just a have look on mandatory part required for a developer to understand exactly what is HTTP this is not full description but it will give you good understanding as web developer.