Tuesday, March 28, 2017

Difference Between Abstract Class and an Interface

What is Difference Between Abstract Class and an Interface:
Today we will discuss the differences between an Interface and Abstract Class. For the beginners, it’s a little bit difficult to understand the concept and difference between them. As we know in C# multiple inheritance is not allowed but we can achieve this by using Interface and this is the main difference between them, A class can implement more than one Interface but can inherit only one abstract class.
However, let’s have a look on some other features and differences.
1. Default Implementation: An interface does not have any type of code implementation it just provides the signature of methods and properties but An Abstract class can have code implementation, definition and may have details to be overridden.
2. Access Modifier: As we know interface provide signature and which is going to implement, this interface, that will define and provide the code implementation so in Interface there is no access modifier all properties and functions are by default public whereas an abstract class can have access modifier for subs, properties and functions.
3. Multiple Inheritance: Interface provide multiple inheritance in C# by inheriting multiple interfaces whereas a class may inherit only one abstract class.
4. Performance: Interfaces are slower than abstract class because an interface requires more time to check the signature and exact method in related classes.
5. Changes or Add New Functions: when we update or add new function to an interface then we have to trace all implementations of interface and need to update all references which is a tough task. In abstract class if we add some new function then we have default code implementation, due to this, all code will work properly no need to change.
Now let's see code implementation.
Abstract Class: abstract class cannot be instantiated so its methods can be called with class name or by using inherited class object.

abstract class ABS_CLS1
{
    public int Addition(int a, int b)
    {
        return (a + b);
    }
}
class Simple_CLS : ABS_CLS1
{
    public int Multiplication(int a, int b)
    {
        return a * b;
    }
}
class Check_Impl
{
    static void Main(string[] args)
    {
        Simple_CLS ob = new Simple_CLS();
        int Total = ob.Addition(5, 10);
        Console.WriteLine("Result is {0}", Total);
        Console.ReadLine();
    }
}


In the above example, we can see, we created the object of class Simple_CLS which inherited our abstract class, so, by using that object we call abstract class method so it clears one more thing abstract class provide the public method in it and also those members which inherited from abstract class's base class.
Interface: interface is not a class, it is by self an entity nominated with word Interface.

interface TestInterface
{
    void testMethod();
}
class CallClass : TestInterface
{
    public static void Main()
    {
        CallClass cls = new CallClass();
        cls.testMethod();
    }
    public void testMethod()
    {
        Console.WriteLine("Called Interface method from implemented class");
        Console.ReadLine();
    }
}


As interface, cannot have code implementation so only one method signature is in interface and calling class have code implementation of that method because its mandatory to calling class implement interface method and properties.
Comments and Suggestions are always welcome!

Sunday, March 26, 2017

Differences between Class and Struct Asp Net


Today we will discuss the difference between class and struct in Asp.Net. As we already know that .Net is object oriented based so it has inside all concepts of OOP with their context.
If you have a little bit idea what is Reference Type and What is Value Type, then it’s very easy to understand the difference between classes and structs because this is the main and first difference in both.
Let's understand with a simple example Reference Type and Value Type:
Basically, structures are Value Type and classes are Reference Type, when we said reference type it shows from the name of this concept.
Reference Type is a reference to some location in the memory and if there is any change in a reference type or class object then it will be reflected on all instances of that object because it’s going to update the referred memory location not specific value on a single position. have a look on below example:

        Class Vehicle
    {
        Public Int NoOfTyres;     
    }


when we will use this class, and create an instance of this class then it will allocate the memory for this instance of this class type and will store the address of memory the class.

        Vehicle Vehicle_car1 =new Vehicle();
    Vehicle_obj1.NoOfTyres=4;
    Vehicle Vehicle_car2 =Vehicle_car1;
    Vehicle_car2.NoOfTyres=6;


In this example, we can check both instances of Vehicle class belong to same memory location because we assign Vehicle_car1 to Vehicle_car2 so they have same location. it also indicates that if there is any change in one it will update both because they both have same reference of memory.
As we update the value of second object Vehicle_car2.NoOfTyres=6; it will set both instances to 6. basically, we are getting NoOfTyres of an object by using different pointers.
But Structures are value type as we discuss earlier,
if we take same example,

        Structure Struct_Vehicle
    {
        Public Int NoOfTyres;     
    }
    
    Struct_Vehicle Str_Car1 =new Struct_Vehicle();
    Str_Car1.NoOfTyres=4;
    Struct_Vehicle Str_Car2 =Str_Car1;
    Str_Car2.NoOfTyres=6;


As per Value type when we create different instance and assign the first to second one then it will make copy of first and assign to second it will not refer to same location in memory. so, by updating the second it will not affect first's value and vice versa.
Value Type always contains a value and reference type can have null reference means it does not refer to anything.
Class also support the inheritance but struct does not.
Classes may have parameter less constructor but struct does not.
Structure cannot have destructors but a class can have a destructor.
Struct are in real an actual value and these can be empty but not null whereas class be referred to null.
Struct are best to use on small data of related groups.
Please share your suggestions and feel free to comments.

Saturday, March 25, 2017

How to format number in javascript jquery


Today we will figure out how to format a number utilizing JavaScript or jQuery. I was taking a shot at a report when I need the add up to be formatted and after some seeking on web I discovered some plugins however I would prefer not to use plugin on my website for such a little errand. At long last I've discovered strategy which works for me so I've chosen to compose a post to impart these little strategies to every one of you. Here I am sharing two strategies so it's your decision to use anybody of them which is appropriate for you.
Function 1 :-
//-----------------Apply comma formation on Amount using JavaScript ------------------

function CommaFormatted(amount) {
            var delimiter = ","; // replace comma if desired
            var a = amount.split('.', 2)
            var d = a[1];
            var i = parseInt(a[0]);
            if (isNaN(i)) { return ''; }
            var minus = '';
            if (i < 0) { minus = '-'; }
            i = Math.abs(i);
            var n = new String(i);
            var a = [];
            while (n.length > 3) {
                var nn = n.substr(n.length - 3);
                a.unshift(nn);
                n = n.substr(0, n.length - 3);
            }
            if (n.length > 0) { a.unshift(n); }
            n = a.join(delimiter);
            if (d.length < 1) { amount = n; }
            else { amount = n + '.' + d; }
            amount = minus + amount;
            return amount;
        }


Function 2:-
 This Function take string as parameter and by using jQuery .test() function and regular expression we are adding comma to the amount.i.e. 2000 will become 2,000

function addCommas(nStr) {
            nStr += '';
            x = nStr.split('.');
            x1 = x[0];
            x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
            }
            return x1 + x2;
        }


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.

Tuesday, March 14, 2017

Difference Between Get and POST

Difference between "Get”, "POST". HTTP stands for Hypertext Transfer Protocol and used for communication from client to server - and vice versa. While working on web development, in daily routine, you must play with HTTP methods it may be Get or Post. Between web and server, a browser will be the client and our hosted application will be server. For Example, when a browser sends an HTTP request to the application(server), in response our application/server returns the status of the request and may have some content also. 

GET: mostly a GET is used to get or retrieve the data from the server. it should not have any side effects. In GET we must embed our data in the URI of request that is the only way. before performing any operation on the data from GET we should first verify. GET request can also be cached by browser and remain in browser history. So, avoid using GET Request when performing some sensitive data operations.
syntax for GET request:

$.get(URL,callback);

Simple call to GET data and alert:

$.get("tutorial_test.aspx", function(data, current_status){
        alert("Here Data: " + data + "\nStatus of Request: " + current_status);
    });

We can set other parameters like: cache parameter false when using ajax GET request like:

$.ajax({ type: "GET", url: "http://domain.com/returnData.html", cache: false, success: function(data){ $("#divResults").append(data); } });

POST: POST method is used to send data to the server. normally in WebApi or Web Services POST is used to insert some record or bunch of data to the database or any file. In POST request, we specify that which type of data we are going to send to the server and then server process the data accordingly. POST request response is not cached by the browser because our POST may have some side effect to the server. POST request should have HTTP Request Body having data to be submitted and in response we can also have response body.
syntax for POST request:

$.post(URL,data,callback);

First and important parameter is URL we want to send request. Secondly, we send our data object which contains data to be processed. In last we have a callback function through which we can check the response and status of the request. Now let have a little example with data, how we will pass data to POST request:

$.post("tutorial_test_post.aspx",
    {
        name: "Final Coding",
        city: "Dubai"
    },
    function(data, Currstatus){
        alert("Response Data: " + data + "\nStatus Received is : " + status);
    });

Monday, March 13, 2017

Turn off Custom Errors in Web config Asp .Net

Custom Error mode off is very common error when you are new to asp.net development. after deploying web to your server you may experience unexpected error Runtime Error to see detail turn off the customErrors in web.config file. in below image we have show the error snapshot.

This type of errors can occur anytime due to some reason it may be there is an extra semicolon in your code but you can not see the details of error whats happening until you set customerrors mode=off in your application web.config file. after setting CustomErros mode to off we can easily see on the web page whats problem and where it occurs which line number and page also.
Basically in Asp.net we have three customErrors mode to check the details and trace the exact problem. these modes tell the browser that it should show full details of errors or not or what message will be shown instead.
Off Mode:

This is used to show the error message details either you are running your application on local or server.

On Mode:

In case of error mostly website show their own 404 page and some suitable error message. when customErrors mode is on then we can set a customError page to display in case of error.
RemoteOnly: RemotelyOnly is the default mode also and it is used to display error message on a remote server only not on local.

What is Web.Config File?

Web.config is a configuration file which contains application's settings/configurations. For a single application only one web.config file is used but if we have to set some configuration for a specific directory then we can make different config file for that directory. For a separate web.config file we have to create same file and we can put some redirection rules for that directory or we can set compression, etc. basically web.config file is xml based which have different tags for particular part of application. we can store database info which includes connections, Set the session expiry time, enable compression for whole application, put Error Handling rules and Security etc. below given some tag of web.config file.

<configuration>
  <configSections>
  </configSections>

  <appSettings>
  </appSettings>

  <connectionStrings>
    <add key="ConnectionName" value="remoteserver=127.1.1.1;uid=sa;pwd=****;database=TestDb" />
  </connectionStrings>

</configuration >

User Controls VS Custom Controls

Today in this tutorials we will learn about user controls and custom controls. So let's start from user controls.

User Controls:-

A user control also can be used a normal server control. Basically user controls are made by user as per their requirements. If a user need to show a news section on all page and should be same on all pages then we can make a user control and put this on all pages. If there is a change in control user will change in control file and it will be replicated to all pages.it is also a best example of code re-usability.

In Asp.net we have System.Web.UI.UserControl class which is used to create user controls.

User control extension is .ascx. A user control cannot have HTML, body or form tags and at the top there is control directive instead of page as used in normal asp.net pages.

Custom Controls:-

Customer control are basically written by user or derived from any third party. Customer control becomes an individual assembly when deployed and after compilation it becomes a DLL (Dynamic Link Library). These can be used as other asp.net server controls. These are used in asp.net web forms and a custom client control used in asp win forms applications. There are different ways to create custom control like:
  1. Derive a customer control from asp.net control
  2. We can compose 2 or 3 asp.net control to derive a new custom control
  3. We can make custom control from base control class of asp.net

Foreach Loop in C#

In this tutorial we are going to learn about foreach loop in c#. So let's start learning
  1. In for loop we use initialization, termination and increment or decrement to loop over the data but in foreach loop we are not required any initialization, condition or increment and decrement. It is a looping constructs which ignore/remove the errors which occur due to index handling.
  2. Mainly it performs its operation on collections like Array, Lists etc. and process inside values one by one.
  3. There are many ways to exit or stop the loop like if we want to break the loop we can use break keyword, if want to move on next iteration continue keyword, to exit the loop we can use return, throw or goto statement.
Syntax:-

foreach(string emp_id in employees)
{

}
Example:-

string[] employees = new string[3]; // declare the array 
    //Add data to array of employees
    array[0] = "Doe-1452";
    array[1] = "Joh-2365";
    array[2] = "Gen-2589"; 
    //show data using foreach
    foreach (string emp_id in employees)
    {
        Console.WriteLine(emp_id + " Entered to Office");
    }
    //Output
    Doe-1452 Entered to Office
    Joh-2365 Entered to Office
    Gen-2589 Entered to Office

Sunday, March 12, 2017

Different types of directives in ASP NET

Different types of directives in .NET? @Page: page directive provide the page related operation/attribute, mainy used in compilation or page parser. it is only written in .aspx file at top, like:
<%@ Page  language="C#" %>

@Control: basically used for asp controls, it provide the control related attributes.only in .ascx files it used.
<%@ Control Language="C#"  %>

@Import: import is used when we are required some additiol namespace and we want to import into a specific page or control. it can have one namespace only.
<% @Import Namespace="System.web"%>

@Implements: it is used to show that this page or user control implements some interface.
<%@ Implements Interface="System.Web.UI.IPostBackEventHandler" %>

@Register: it is used to add a control and for that we require to register it first, by using this we can specifically add a customer server control or some user control or skin file.
<%@ Register Tagprefix="uc1" Tagname="AdGrids" Src="AdGrids.ascx" %>

@Assembly: Basically it gives access to an assembly for that page. it makes all classes and methods accessible on the page.
<%@ Assembly Name="BarCode" %>

@OutputCache: output cache is a technique to enable cache on that page.
<%@ OutputCache Duration="60" VaryByControl="*" %>

@Reference: In which page this directive is declared it shows that page/control sholuld first complete compile and link to this page.

Caching best practices and difference between OutputCache Vs Data Cache in Asp.Net


1. Page Level Output Caching

This is simple form and very easy to implement.basically Output Cache save a copy of html and when again client request for same html it will send in response from cache untill or unless that cache is not expired by using this we can have a very good performance rate and response time.

for implementation of output cache on page, simply we need to add OutputCache directive to the page.


<%@ OutputCache Duration = "60" VaryByParam= "*" %>


This directive will be shown at the top of the page same like to other directives of the page:   OutputCache supports 5 parameters in which two are required "Duration" and "VaryByParam".


Duration: (mandatory) keeps the time in seconds,for how much time we want to store cache.

VaryByParam: (mandatory) Here we can mention the names of the variables, which will be result in separate for each entry. it have a "none" parameter which can be used for no variation. mostly used parameter  is "*",is used to create a new entry in cache for different variable.but we have to separate the variables with ";" for more than one variation.

Location: (optional) In location we mention that where our cache will be cached it support different parameter like Any, Client, Downstream, None, Server or ServerAndClient.

VaryByHeader: (optional) Cache entries can be changed by using this parameter it check the variation in the header and accordingly.

VaryByCustom: (optional) it allow the custom variations which can be specified in the global.asax (e.g. "Browser").

2.Fragment Cache or User Control Cache

As its name shown fragment Caching,Most of the time we have such requirements thats we dont want to cache the whole page because that are customized to user data so in such cases where we are required to cache only specific part of page and other should not b part of cache then we will use Fragment Cache. To have different data in a page mostly we prefer to use user control which are best in performance and can be customized easily.

Examples

<%@ OutputCache Duration="60" VaryByParam="*" %>

This will cache the control for 60 seconds only and it will have separate entry for each variation in url query string and every page on which this control is added.


<%@ OutputCache Duration="60" VaryByParam="none" VaryByControl="CategoryDropDownList" %>

This will also cache the control for 60 seconds but for each value of DropDownList and on each page.


e.g. <%@ OutputCache Duration="60" VaryByParam="none" VaryByCustom="browser" shared="true %>


Shared= true make sure that in all pages it will have only one entry and all page which have same control with same id will share the cache and there will be single entry for a single browser.

3. API Caching/Data Caching Using Cache object:

Other than cache a page or control we can also cache an object it may contain xml or database return object, Page Cache and Control cache is very easy and can be done in short time whereas API cache or Data cache reuires little programming. for this Asp.net provides the cache object like session and cookies. Cache ["keyname"] = "value"; it will store value in cache without any dependencies and it will remain cached untill or unless we remove it from cache. Asp.net provides Add() and Insert() method to implement other dependencies.

To cache the whole xml file we will have below format:

Cache.Insert("key", XMLFileDataCache, new System.Web.Caching.CacheDependency(Server.MapPath("users.xml")));

so again and again no need to read data from the file once its cached then on each request we can retrive data from cache and it will also increase performance.cache will be expired whenever there is any change in xml file.

Cache.Insert("dependentkey", myDependentData, new System.Web.Caching.CacheDependency(new string[] {}, new string[]

  {"key"}));

To store an array of data into cache we can use above format.it depends upon the value key, it will expire the cache if key does not exists or updated.


Cache.Insert("key", myTimeSensitiveData, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero);

Here we are using absolute expiration that means we will cache the data for a specific time or we will store the data which depends upon time interval after that time cache will expire automatically.

Cache.Insert("key", myFrequentlyAccessedData,null,  System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(1));

This is sliding expiration that means if cache is not used for a specific time then it will expire. in above example if there is no access to cache for 1 minute it will be expired.absolute and soliding expiration is not possible to use same time.