jQuery exception handling

There are two types of Exceptions which is caught by jQuery

1. When exception object is in the form of JSON object.

2. When exception object is in the form of plain text or HTML.


WebMethod for testing both types

In order to test both the cases I have created the following WebMethod which simply tries to convert the received string value to integer.

[System.Web.Services.WebMethod]

public static void ValidateNumber(string number)

{

    int no = Convert.ToInt32(number);

}

function tc(func, msg) {

  msg = msg || "Handler exception";

  return function(e) {

    try {

      return func(e);

    }

    catch (exc) {

      $.post( /* send exception to server? */ );

      throw exc; // let nature take its course

    }

  };

}

___________________________________________________________________________________

try {   // Your code goes here… }

catch(err) { // Handle the error here. }

finally { // Code always executed regardless of the result.

}

___________________________________________________________________________________

jQuery.readyException() - Handles the errors thrown synchronously in functions wrapped in $.jQuery. 

By default it re-throws the error in a timeout so that it's logged in the console and passed to window.onerror instead of being swallowed.

jQuery.readyException = function(error) {

  console.error( error );

}; 

___________________________________________________________________________________


Abstract Class vs Interface

Abstract Class:
Abstract class is a class that contain complete and abstract (incomplete) both type of member and it can not be instantiated.

Interface:
Interface is a type which contains only the signatures of methods, delegates or events, it has no implementation. Implementation of the methods is done by the class that which implements the interface. Interface is a type which contains only the signatures of methods, delegates or events, it has no implementation, Implementation of the methods is done by the class that which implements the interface.


Difference between Abstract Class and Interface
Abstract ClassInterface
It contains both declaration and definition part.It contains only a declaration part.
Multiple inheritance is not achieved by abstract class.Multiple inheritance is achieved by interface.
It contain constructor.It does not contain constructor.
It can contain static members.It does not contain static members.
It can contain different types of access modifiers like public, private, protected etc.It only contains public access modifier because everything in the interface is public.
The performance of an abstract class is fast.The performance of interface is slow because it requires time to search actual method in the corresponding class.
It is used to implement the core identity of class.It is used to implement peripheral abilities of class.
A class can only use one abstract class.A class can use multiple interface.
If many implementations are of the same kind and use common behavior, then it is superior to use abstract class.If many implementations only share methods, then it is superior to use Interface.
Abstract class can contain methods, fields, constants, etc.Interface can only contain methods .
It can be fully, partially or not implemented.It should be fully implemented.

ABCs of an EndPoint in WCF

WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world. All the WCF communications are take place through end point. End point consists of three components.

Address

Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service.
HTTP It's a protocol for communication over the web (uses TCP at a lower level).
TCP High performance communication in WCF. Good for intranet scenarios.
Named Pipe Fast and reliable communication between client and server running on the same machine.
MSMQ Used when the client enqueues a message that a service can then consume later.

e.g :  

http://localhost:8090/MyService/SimpleCalculator.svc
net.tcp://localhost:8001/Service
net.pipe://localhost/Service
net.msmq://localhost

Binding

Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.
A binding has several characteristics, including the following:
  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability
The following table gives some list of protocols supported by WCF binding.
Binding Description
BasicHttpBinding Basic Web service communication. No security by default
WSHttpBinding Web services with WS-* support. Supports transactions
WSDualHttpBinding Web services with duplex contract and transaction support
WSFederationHttpBinding Web services with federated security. Supports transactions
MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding Communication between WCF applications across computers. Supports duplex contracts and transactions

 

Contract

Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.



Below figure illustrate the functions of Endpoint

 



 
Endpoints will be mentioned in the web.config file on the created service.
Example :
<system.serviceModel>
    <services>
      <service name="MathService"  behaviorConfiguration="MathServiceBehavior">
        <endpoint address="http://localhost:8090/MyService/MathService.svc" contract="IMathService" binding="wsHttpBinding"/> 
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
</system.serviceModel>
  

Unit Testing

Visual Studio includes a Live Unit Testing feature that allows you to see the status of passing/failing tests as you’re typing your code. This feature is only available in the Enterprise Edition of Visual Studio.

The simplest unit test usually includes three distinct steps: Arrange, Act and Assert.

Arrange: Set up the any variables and objects necessary.

Act: Call the method being tested, passing any parameters needed

Assert: Verify expected results

The unit test project should have a dependency for the app project that it’s testing. 

In the test project file NetLearner.Mvc.Tests.csproj;

<ItemGroup>

   <ProjectReference Include="..\NetLearner.Mvc\NetLearner.Mvc.csproj" />

</ItemGroup>

Magic Table in SQL Server

Magic tables are nothing but the logical tables, maintained by SQL server internally.
We can not see or access these tables directly, not even their data-type. The only method to have access to these tables is Triggers operation either After Trigger or Instead of trigger.
There are two types of Magic tables available in SQL server:
1. Inserting into Table (Inserted Table):
Whenever we do  insert anything in our base table in database, a table gets created automatically by the 
SQL server, named as INSERTED. In this table current updated or inserted record will be available. we can access this table of record via triggers.
2. Deleting (Deleted Table):
Whenever we do deletion in base table in database, a table gets created automatically by the SQL server, named as
DELETED table. This table consist of current updated record after deletion operation. Again we can have access to these records via triggers.



C Sharp - Convert to byte

 
byte[]  byteContent = null;
byteContent = (byte[])System.Text.Encoding.UTF8.GetBytes(yourString);
  you can store it as image in database


get data from database,etc
byte[] bytes = e.Result[0].jobdes; 

convert image into string.
textbox.text = UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length);

SQL

Differences between Stored Procedures and triggers

1. When you create a trigger you have to identify event and action of your trigger but when you
    create s.p you don't identify event and action

2.Trigger is run automatically if the event is occured but s.p don't run automatically but you have to
    run it manually

3. Within a trigger you can call specific s.p but within a SP you cannot call a trigger.

4.Trigger execute implicitly whereas store procedure execute via procedure call from another block.

5.We can call a stored procedure from front end (.asp files, .aspx files, .ascx files etc.) but we can't
    call a trigger from these files.

6. Stored procedure can take the input parameters, but we can't pass the parameters as an input to a
     trigger.

 Stored Procedure  and  Function in SQL Server
  1. Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
  2. Functions can have only input parameters for it whereas Procedures can have input/output parameters .
  3. Functions can be called from Procedure whereas Procedures cannot be called from Function.


    -------------------------------------------------------------------------------------------------------------------

Indexes are used to speed-up query process in SQL Server, resulting in high performance. They are similar to textbook indexes. In textbooks, if you need to go to a particular chapter, you go to the index, find the page number of the chapter and go directly to that page. Without indexes, the process of finding your desired chapter would have been very slow. On the other hand, if you create indexes, the database goes to that index first and then retrieves the corresponding table records directly.

There are two types of Indexes in SQL Server :
1. Clustered Index
2. Non-Clustered Index

Clustered Indexes
A clustered index defines the order in which data is physically stored in a table. Table data can be sorted in only way, therefore, there can be only one clustered index per table. In SQL Server, the primary key constraint automatically creates a clustered index on that particular column.
  • A Table can have ONLY 1 Clustered Index.
  • A Clustered Index always has Index Id of 0.
  • A Primary Key constraint creates a Clustered Index by default.
  • A Primary Key constraint can also be enforced by Nonclustered Index, You can specify the index type while creating Primary Key.
  • If the table does not have Clustered Index it is referred to as a "Heap".
  • The leaf node of a Clustered Index contains data pages of the table on which it is created.
  • Clustered Index enforces a logical order on the rows. Rows are ordered based on Clustering Key.
Non-clustered Indexes
A non-clustered index doesn’t sort the physical data inside the table. In fact, a non-clustered index is stored at one place and table data is stored in another place. This is similar to a textbook where the book content is located in one place and the index is located in another. This allows for more than one non-clustered index per table.
When a query is issued against a column on which the index is created, the database will first go to the index and look for the address of the corresponding row in the table. It will then go to that row address and fetch other column values. It is due to this additional step that non-clustered indexes are slower than clustered indexes.
  • Prior to SQL Server 2008 only 249 Nonclustered Indexes can be created. With SQL Server 2008 and above 999 Nonclustered Indexes can be created.
  • Nonclustered Indexes have Index Id > 0.
  • A Unique Key constraint created a Nonclustered Index by default.
  • A Unique Key constraint can also be enforced by Clustered Index, You can specify the index type while creating Unique Key
  • Nonclustered Index does not order actual data, It only orders columns present in the Nonclustered Index based on Index Key specified at the time of creation of Nonclustered Index.
  • A table may not have any Nonclustered Indexes.
  • The leaf nodes of a Nonclustered Index consists of Index pages which contain Clustering Key or RID to locate Data Row.
  • When Clustered Index is not present leaf node points to Physical Location of the row this is referred to as RID. When a Clustered Index is present this points to Clustering Key (Key column on which Clustered Index is created).

.NET Design Pattern in C#

Design patterns
     Design patterns provide general solutions or flexible way to solve common design problems.  Design Patterns in object oriented world is reusable solution to common software design problems which occur again and again in real world application development. It is a template or description for how to solve a problem which can be used in many different situations.


23 patterns are grouped into three main categories :

    Creational Design Pattern
        Factory Method
        Abstract Factory
        Builder
        Prototype
        Singleton
    Structural Design Patterns
        Adapter
        Bridge
        Composite
        Decorator
        Façade
        Flyweight
        Proxy
    Behavioral Design Patterns
        Chain of Responsibility
        Command
        Interpreter
        Iterator
        Mediator
        Memento
        Observer
        State
        Strategy
        Template Method
        Visitor
     

--------------------------------------------------------------------------------------------------------------------------


Creational Patterns

1. Factory Method
Factory Method define an interface for creating an object, but let sub-classes decide which class to instantiate. Factory Method lets a class defer instantiation to sub-classes.

2. Abstract Factory
Abstract Factory provide an interface for creating families of related or dependent objects without specifying their concrete classes.

3. Builder
Builder separate the construction of a complex object from its representation so that the same construction process can create different representations.

4. Prototype
Prototype specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.

5. Singleton
Singleton pattern can be implemented interfaces. It helps to hide dependencies. Singleton ensure a class has only one instance and provide a global point of access to it. It provides a single point of access to a particular instance, so it is easy to maintain.


Structural Patterns

6. Adapter
Adapter convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

7. Bridge
Bridge decouple an abstraction from its implementation so that the two can vary independently.

8. Composite
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

9. Decorator
Decorator attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality.

10. Facade
Facade provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.

11. Flyweight
Flyweight use sharing to support large numbers of fine-grained objects efficiently.

12. Proxy
Proxy provide a surrogate or placeholder for another object to control access to it.


Behavioral Patterns

13. Chain of Responsibility
Chain of Responsibility avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

14. Command
Command encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

15. Interpreter
Interpreter given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

16. Iterator
Iterator provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

17. Mediator
Mediator define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

18. Memento
Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.

19. Observer
Observer define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

20. State
State allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

21. Strategy
Strategy define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

22. Template Method
Define the skeleton of an algorithm in an operation, deferring some steps to sub-classes. Template Method lets sub-classes redefine certain steps of an algorithm without changing the algorithm's structure.

23. Visitor
Visitor represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Understanding IEnumerable, IQueryable, ICollection, IList in C#

IEnumerable
The IEnumerable is used to iterate a read only collection. It has only one method GetEnumeartor() which allows you to iterate the read only collection using a foreach loop. It only iterates in the forward direction. 
Some of the important points about IEnumerable is as follows:
  • It is a read only collection.
  • It iterates only in forward direction.
  • It does not support adding, removing objects on collection.
  • It provides enumerator to iterate collection in forward direction.

If you are fetching records from remote databases IQueryable should be used. It constructs the query using an Expression Tree. On the other hand in the IEnumerable the query is constructed using delegates. Both IQueryable and IEnumerable support lazy loading of data from remote database servers.
Some of the important points about IQueryable are as follows:
  • It implements IEnumerable so the results can be iterated using foreach
  • It is best suited to query against external data sources.
  • It creates query using an Expression Tree
  • It is used to query a queryable data source

IQueryable:
  • query isn't executed until you really iterate over the items, maybe by doing a .ToList() or a foreach
  • extends IEnumerable
IEnumerable:
  • forward-only list of items. You can't get at "item 4" without passing items 0-3.
  • read-only list, you can't add to it or remove from it.
  • Still might use deferred execution.
IList:
  • random access to the full list
  • entirely in memory
  • supports adding and removing
  • extends IEnumerable and ICollection
ICollection:
  • Is between IEnumerable and IList.
  • extends IEnumerable



Which type should you depend on?

Now that we have looked at all of the interfaces in question, we are ready to decide which interface we should depend on in which situation. Generally it’s a great idea to only depend upon things we really need. I am going to show you how this decision can be made very easily and what you can expect to gain if you do so.
If you use a more narrow interface type such as IEnumerable instead of IList, you protect your code against breaking changes. If you use IEnumerable, the caller of you method can provide any object which implements the IEnumerable interface. These are nearly all collection types of the base class library and many custom defined types in addition. The caller code can be changed in the future and your code won’t break that easily as it would if you had used ICollection or even worse IList.
If you use a wider interface type such as IList, you are more in danger of breaking code changes. If someone wants to call your method with a custom defined object which only implements IEnumerable it simply won’t work and result in a compilation error.
Generally you should always use that type that provides a contract for only the methods you really use.

The following table gives you an overview of how you could decide which type you should depend on.
Interface Scenario
IEnumerable, IEnumerable The only thing you want is to iterate over the elements in a collection. You only need read-only access to that collection.
ICollection, ICollection You want to modify the collection or you care about its size.
IList, IList You want to modify the collection and you care about the ordering and / or positioning of the elements in the collection.
List, List Since in object oriented design you want to depend on abstractions instead of implementations, you should never have a member of your own implementations with the concrete type List/List.

HTML Helpers In ASP.NET MVC

It provides an easy way to Render HTML in our View.

The following is the list of Html Helper controls.
Html.Beginform
Html.EndForm
Html.Label
Html.TextBox
Html.TextArea
Html.Password
Html.DropDownList
Html.CheckBox
Html.RedioButton
Html.ListBox
Html.Hidden


Below are Strongly Type Html Helper methods, this will allow us to check compile time errors.
Html.LabelFor
Html.TextBoxFor
Html.TextAreaFor
Html.DropDownListFor
Html.CheckBoxFor
Html.RadioButtonFor
Html.ListBoxFor
Html.HiddenFor