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