Friday 21 November 2014

Email validation at Database with check constraint

 create table t_superheros (   id   int  , name    nvarchar(14), [Email]   nvarchar(20) CONSTRAINT [EmailValidator]
CHECK
(
CHARINDEX(' ',LTRIM(RTRIM([Email]))) = 0 -- No embedded spaces
AND LEFT(LTRIM([Email]),1) <> '@'  -- '@' can't be the first character of an email address
AND RIGHT(RTRIM([Email]),1) <> '.' -- '.' can't be the last character of an email address
AND CHARINDEX('.',[Email],CHARINDEX('@',[Email])) - CHARINDEX('@',[Email]) > 1 -- There must be a '.' after '@'
AND LEN(LTRIM(RTRIM([Email]))) - LEN(REPLACE(LTRIM(RTRIM([Email])),'@','')) = 1 -- Only one '@' sign is allowed
AND CHARINDEX('.',REVERSE(LTRIM(RTRIM([Email])))) >= 3 -- Domain name should end with at least 2 character extension
AND (CHARINDEX('.@',[Email]) = 0 AND CHARINDEX('..',[Email]) = 0) -- can't have patterns like '.@' and '..'
));

Thursday 20 November 2014

Encode and decode

Encode

public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}

Decode


public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

Tuesday 11 November 2014

Partial Classes



It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

There are several situations when splitting a class definition is desirable:
  • When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.
  • When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.

Example:

       Program that uses partial class: C#
      
       class Program
       {
           static void Main()
           {
              A.A1();
              A.A2();
           }
       }
      
       Contents of file A1.cs: C#
      
       using System;
      
       partial class A
       {
           public static void A1()
           {
              Console.WriteLine("A1");
           }
       }
      
       Contents of file A2.cs: C#
      
       using System;
      
       partial class A
       {
           public static void A2()
           {
              Console.WriteLine("A2");
           }
       }
      
       Output
      
       A1

       A2

Thursday 6 November 2014

Ajax

Ajax
·      AJAX = Asynchronous JavaScript and XML.
·      AJAX is not a new programming language, but a new way to use existing standards.
·      AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.

AJAX is based on internet standards, and uses a combination of:
  • XMLHttpRequest object (to exchange data asynchronously with a server)
  • JavaScript/DOM (to display/interact with the information)
  • CSS (to style the data)
  • XML (often used as the format for transferring data)

The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object
All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable=new XMLHttpRequest();
Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:
variable=new ActiveXObject("Microsoft.XMLHTTP");

 GET Requests
A simple GET request:
Example
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();


In the example above, you may get a cached result.
To avoid this, add a unique ID to the URL:
Example
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();
If you want to send information with the GET method, add the information to the URL:
Example
xmlhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford",true);
xmlhttp.send();


POST Requests
A simple POST request:
Example
xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method:
Example
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
  
The onreadystatechange event
When a request to a server is sent, we want to perform some actions based on the response.
The onreadystatechange event is triggered every time the readyState changes.
The readyState property holds the status of the XMLHttpRequest.
Three important properties of the XMLHttpRequest object:
onreadystatechange
Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState
Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status
200: "OK"
404: Page not found


Example:
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.asp?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>


AJAX Interview Questions


Interview Questions

1.Define AJAX?

AJAX stands for "Asynchronous JavaScript and XML". It's basically a technique for creating Rich Internet 
Applications (RIA) that are faster as well as more interactive, using a combination of commonly used techniques as HTML/XHTML, CSS, Document Object Model (DOM), JavaScript, XML/XSLT and XMLHttpRequest object.
XMLHttpRequest object is the key basis of AJAX and makes it possible to communicate with the web server asynchronously and exchange data.

2.Please elaborate XMLHttpRequest Object further?

XMLHttpRequest is the core object in AJAX technology regardless of any implementation. XMLHttpRequest object is used to exchange data with a server seamlessly. Basically JavaScript uses this Object to exchange XML as well as text data between client and server. An AJAX implementation uses this object and communicate with server but it doesn't require the complete page to be refreshed.

3.How to send a request to server using XMLHttpRequest Object?

We can send a request to server using HTTP GET and POST methods as follows:

//Simple GET Request
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "TestFile.txt", true);
xmlHttp.send();

//Simple POST Request
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "TestFile.txt", true);
xmlHttp.send();


4.What is ASP.NET AJAX?

Microsoft provided an implementation of AJAX functionality known as ASP.NET AJAX.
As we discussed in above interview question that AJAX is a combination of various techniques, so Microsoft simplified the usage of these techniques with its own implementation. ASP.NET AJAX is a set of extensions to ASP.NET and comes with reusable AJAX controls. Using ASP.NET AJAX, we can develop applications that can update partial page instead of a complete page refresh.

5.Difference between Synchronous and Asynchronous Postback?

In Synchronous postback, complete web page is sent to server and in return rendering the output (i.e. complete page), whereas in case of Asynchronous postback, partial page goes to the server and renders only partial (required) part of the page.

6.What are the basic controls in ASP.NET AJAX?

Following controls can be considered as core AJAX controls in ASP.NET.
·         ScriptManager
·         ScriptManagerProxy
·         UpdatePanel
·         UpdateProgress
·         Timer
Later more controls are added to ASP.NET AJAX library e.g. Script Loader, Client Data Context, Client Data Access, jQuery Integration etc.

7.What is a ScriptManager in ASP.NET AJAX?

In order to use AJAX functionality on a web page, we add a ScriptManager control to the page in most of the scenarios, because ScriptManager control register AJAX library scripts to that particular web page. We can have only one ScriptManager per page.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

ScriptManager basically manages all ASP.NET AJAX resources of a web page, creates proxies for asynchronous web service call and also manages partial page updates... etc.

8.ScriptManager Vs ScriptManagerProxy?

As we understand that we can have only one ScriptManager control on a page but we can have multipleScriptManagerProxy controls.
Consider a scenario that we have ScriptManager in our MasterPage that is available for all content pages. Now, we wanted to register a web service in a particular page. So, we will not add another ScriptManager to that page instead we will add ScriptManagerProxy to it in order to avoid error.

9.What is the role of UpdatePanel in ASP.NET AJAX?

UpdatePanel is the control that facilitate the partial page rendering functionality in an ASP.NET application. As discussed earlier that using ASP.NET AJAX, we can communicate with a web server asynchronously and update a part of a page without a complete page postback. In order to apply partial page update/rendering, we can add one or more UpdatePanel controls to our ASP.NET Page as follows:
   <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
     <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Label ID="lblPanel" runat="server" Text="Update Panel Added."></asp:Label><br />
                <asp:Button ID="btnTestButton" 
                                   runat="server" 
                                  OnClick="btnTestButton_Click" 
                                  Text="Test Button" />
      </ContentTemplate>
    </asp:UpdatePanel>

10.What are the limitations of AJAX?

·         AJAX on an application will not work if JavaScript is disabled.
·         In some scenarios, it exposes vulnerability.
·         It will always be difficult to bookmark application state.
·         Application behavior may be slow in some scenarios, because of different loading time of controls on a single page.

11. What are the new features included in the Microsoft AJAX library?
The Microsoft AJAX library is a client-based JavaScript library that is compatible with all modern browsers and offers a lot of functionality as compared to JavaScript. This library is released with new features and fully supports ASP.NET 4.0'. The new features included in the Microsoft AJAX library are as follows:
  • Imperative syntax - Supports simple imperative syntax that is used to create and manage controls.
  • Script loader - Retrieves all scripts that are needed by one or more client component or control automatically and executes the scripts in the order in which they are received.
  • Client data access - Supports to access client data and display by client data control and client template.
  • Client datacontext - Supports read and write permission to data from a database.
  • The AdoNetDataContext class - Enables you to easily interact with an ADO.NET Data Services service.
  • jQuery integration - Helps to access the elements in your Web pages, work with client-side events, enable visual effects, and make it easier to use AJAX in your applications.
12. Explain the Step property of the NumericUpDownExtender control.
The Step property sets the steps for numeric increment and decrement. The default value is 1.

13. What are the new features of ASP.NET AJAX 4.0?
ASP.NET 4.0 AJAX includes several new features that provide more functionality to a user. These features are as follows:
  • Support for live data binding.
  • Support for client-side template rendering.
  • Support for declarative instantiation of client components.
  • Support for using the observer pattern on JavaScript objects and arrays.
  • Support for invoking ADO.NET data services and data contexts.
  • Support for the DataView control.
14. Why do we use the UpdateProgress control in AJAX?
The UpdateProgress control is somewhat related to the UpdatePanel control. The UpdateProgress control enables you to design a user-friendly interface when a Web page consists of a number of UpdatePanel controls for partial-page rendering.

The UpdateProgress control makes you aware of the status information about the partial-page updates in theUpdatePanel control.

15. What is JSON?
JSON is an abbreviation of JavaScript Object Notation. It is a safe and reliable data interchange format in JavaScript, which is easy to understand not only for the users but also for the machines.

16. How many validation controls are available in ASP.NET AJAX 4.0?
The following validation controls are available in ASP.NET AJAX 4.0:
  • FilteredTextBoxExtender - Enables you to apply filtering to a text box.
  • MaskedEditExtender and MaskedEditValidator - Restricts a user to enter only a certain pattern of characters in the TextBox by applying a mask to the input.
  • ValidatorCalloutExtender - Attaches to the ASP.NET validators so that the error messages are not displayed as a simple text but as a balloon-style ToolTip.
  • NoBot - Prevents the spam/bot from filling the input forms automatically and uses the Completely Automated Public Turing test to tell Computers and Humans Apart (CAPTCHA), which is a type of challenge-response test to ensure that the response is not generated by the computer.
  • PasswordStrengthExtender - Measures the strength of the password text entered within the text box by validating with the different strength specified parameters
17. What are the differences between AJAX and JavaScript?
The differences between AJAX and JavaScript are given as follows:
  • AJAX sends request to the server and does not wait for the response. It performs other operations on the page during that time. JavaScript make a request to the server and waits for response.
  • AJAX does not require the page to refresh for downloading the whole page while JavaScript manages and controls a Web page after being downloaded.
  • AJAX minimizes the overload on the server since the script needs to request once while JavaScript posts a request that updates the script every time.
18. Explain the UpdatePanel control.
The UpdatePanel control specifies the portions of a Web page that can be updated together. As the UpdatePanelcontrol refreshes only a selected part of the Web page instead of refreshing the entire page with a postback, you get more flexibility to create rich and client-centric Web applications.

Refreshing a selected part of the Web page is referred as partial-page update. You can add one or more UpdatePanelcontrol in the Web page, which automatically participates in partial-page update without custom client script. TheUpdatePanel control uses the UpdatePanel class to support the partial-page rendering.
19. What does the DynamicPopulateExtender control do?
The DynamicPopulateExtender control populates the contents of a control dynamically. It enables you to send an asynchronous call to the server that dynamically populates the contents of a control. TheDynamicPopulateExtender control replaces the contents of a control with the result of a Web service or page method call.

20. What does the MinimumPrefixLength property of the AutoCompleteExtender control do?
The MinimumPrefixLength property sets the minimum number of characters that must be entered before getting suggestions from the Web service.

21. What is the importance of client-side libraries?
Client-side libraries contain built-in code to make asynchronous calls over XMLHTTP. These libraries automatically handle browser compatibility issues. These libraries are based on a programming model similar to ASP.NET

22. Describe the situations in which AJAX should not be used.
You should not use AJAX if:
  • You want the page to show in a search engine, such as Google, because WebCrawler does not execute JavaScript code.
  • The browser does not support JavaScript.
  • You want to create a secure application.
23. What is the use of the ScriptManager control in AJAX?
·         The ScriptManager control is a core control that performs a key role in implementing the ASP.NET AJAX functionality. It helps to use JavaScript for the Microsoft AJAX Library. It should be noted that AJAX Library on a Web page can only be used if the Web page contains the ScriptManager control. This control makes use of theScriptManager class to maintain the AJAX script libraries and script files. It allows for partial page rendering, Web service calls, and use of ASP.NET AJAX Client Library by rendering the AJAX Library scripts to the browser.

24. How can you find out that an AJAX request has been completed?
·         You can find out that an AJAX request has been completed by using the readyState property. If the value of this property equals to four, it means that the request has been completed and the data is available.

25. Describe the AccordionExtender control.
·         The AccordionExtender control is similar to the CollapsiblePanelExtender control. It allows you to group multiple collapsible panels in a single control. At the same time, it also manages the collapsed and expanded state of each panel; therefore, expanding one panel at a time. In other words, the AccordionExtender control does not support expanding two or more panels simultaneously. Instead, the header templates of all the panels are always visible so that you can click on any of them to display the hidden contents. By default, the AccordionExtendercontrol opens with one panel as expanded.


Example:Call webservice from javascript
Welcome to the "Understand jQuery Ajax Function" article series. This series is targeted to novice developers that want to learn Ajax using the JQuey Ajax function. The previous example explained about calling a code-behind C# method using a jQuery Ajax function. You can read it here.

Understand jQuery Ajax function: Call code-behind C# method using jQuery Ajax method

In this article we will see how to call Web Service methods using a jQuery Ajax function. In a future article we will proceed to a WCF Service and the Web API.

Call Web Service from JQuey Ajax function

We will now call a C# Web Service method using a jQuery Ajax method. Try to understand the following code.

Step 1: Create simple web service

This is the first step, here we will create a simple web service that will be consumed by a JQuey Ajax method. So add one .asmx page to the current solution and modify the code as in the following example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace WebApplication
{
   
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class DataService : System.Web.Services.WebService
    {

        [WebMethod]
        public string GetData()
        {
            Dictionary<string, string> name = new Dictionary<string, string>();
            name.Add("1", "Sourav Kayal");
            name.Add("2", "Ram mishra");
            string myJsonString = (new JavaScriptSerializer()).Serialize(name);
            return myJsonString;
        }
    }
}

As in the previous article, the code is very simple . Here are two things we need to keep in mind.

Don't forget to enable the attribute:

[System.Web.Script.Services.ScriptService]

Before the class definition. The second one is to add the "[WebMethod]" attribute before the function definition. So, here we have finished our Service settings. We can run this service to test it in a Web browser. Now we will set up a jQuery Ajax function to call the service.

Step 2: Implement jQuery Ajax function

Here is sample code to call Web Service method. The only changes we made compared to the code-behind fashion (in the previous article) is the URL. Here we specified the service location of the specific C# function.

In this context there is one more point to explain. In the case of the code-behind fashion we declared the C# method as a static method, but for the Web Service, it is not necessary to define the method as a static method.
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs"Inherits="WebApplication.JavaScript" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script>

     $(document).ready(function () {

         $.ajax({
             type: "POST",
             url: "DataService.asmx/GetData",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: function (response) {
                 var names = response.d;
                 alert(names);
             },
             failure: function (response) {
                 alert(response.d);
             }
         });
     });
 </script>
</head>
<body>

<form id="frm" method="post">
    <div id="Content">

    </div>

</form>

</body>
</html>

Here is sample output.