Friday, February 23, 2018

Introduction of MapReduce

MapReduce is the processing layer of Hadoop. MapReduce programming model is designed for processing large volumes of data in parallel by dividing the work into a set of independent tasks. You need to put business logic in the way MapReduce works and rest things will be taken care by the framework. Work (complete job) which is submitted by the user to master is divided into small works (tasks) and assigned to slaves.
It contains the task of data processing and distributes the particular tasks across the nodes. It consists of two phases –
  • Map
  • Reduce
Map converts a typical dataset into another set of data where individual elements are divided into key/value pairs.
Reduce task takes the output files from a map considering as an input and then integrate the data tuples into a smaller set of tuples. Always it is been executed after the map job is done.

Features of Mapreduce system
Features of Mapreduce are as follows:
  • Framework is provided for Mapreduce execution
  • Abstracts developer from the complexity of distributed programming languages.
  • Partial failure of the processing cluster is expected and tolerable to fulfill the requirements.
  • In-built Redundancy and fault tolerance is available.
  • Mapreduce programming model system is language independent.
  • Automatic parallelization and distribution are in charge.
  • Fault tolerance
  • Enable data local processing
  • Shared nothing than architectural model
  • Manages all the inter process communication
  • Parallelly managing the distributed servers which are running across the various tasks.
  • Managing all communications and data transfers between the various part of system module.
  • Redundancy and failures are provided for overall management of the whole process.

Mapreduce simple steps follow:

  1. Executes map function on each input is received
  2. Map function emits key, value pair
  3. Shuffle, Sort and Group the outputs
  4. Executes the reduce function on the group
  5. Emits the output results is given per group basis.

Map Function

Mainly operates on each key/value pair of data and then transforms the data based on the transformation logic provided in the map function. Map function always produces a key/value pair as output result.
Map (key1, value1) ->List (key2, value2)

Reduce Function

It takes list of value for each and every key transforms the data based on the (aggregation) logic provided in the reduce function.
Reduce (key2, List (value2)) ->List (key3, value3)
Map Function for Word Count
private final staic IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map (LongWritable key, Text value, Context context)

throws IOException, InterruptedException{ String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line); while(tokenizer.hasMoreTokens()){ word.set(tokenizer.nextToken()); context.write(word, one); } } Reduce Function for Word Count public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException{ int sum = 0; for(IntWritable val: values){ sum+=val.get(); } Context.write(key, new IntWriatble(sum)); }

MapReduce is the framework that is used for processing large amounts of data on commodity hardware on a huge dataset of cluster ecosystem. The MapReduce is a powerful method of processing data when there are large amounts of node connected to the cluster. The two important tasks of the MapReduce algorithm are: Map and Reduce.
The main motto of the Map task is to take a large set of data and convert it into another set of data which is broken down into tuples(rows) or Key/Value pairs. Later the Reduce task takes the tuple which is the form of an output of the Map task and makes the input for a reduction task. Here the data tuples are converted into a very smaller set of tuples. The Reduce task always follows as per the Map task.
The biggest strength of the MapReduce framework is its scalability. Once a MapReduce program is written then it can be easily extrapolated to work over a cluster which has hundreds or even thousands of nodes within it. In this framework, actually computation is sent to where the data resides.

Terminology

PayLoad– These are the applications that are implemented for the Map and Reduce functions.
Mapper– This application helps to maps the input key/value pairs to a set of intermediate key/value pair.
NamedNode– This node manages the HDFS.
DataNode– DataNode is used where data is presented in a before any processing takes place.
MasterNode– MasterNode is used where JobTracker runs and receives job requests from clients.
SlaveNode– Map and Reduce program run particularly in this node.
JobTracker– This schedules the jobs and tracks the assigns the jobs to Task tracker.
Task Tracker– the Task Tracker status is reported to JobTracker after the task is being tracked.
Job– It is an execution process of a Mapper and Reducer.
Task– Task of an execution of a Mapper or a called as Reducer on a slice of data.
Task Attempt– This is an attempt to execute a task on a SlaveNode.




Saturday, July 20, 2013

Numeric Field Accept Only Defined decimal and Numeric Part And Block Non Numbers

function extractNumber(obj, numericPlaces, decimalPlaces, allowNegative, e) {
    //debugger;
    var temp = obj.value;
    // avoid changing things if already formatted correctly
    var ctrlDown;
    var akey = 65, vKey = 86, cKey = 67;

    ctrlDown = e.ctrlKey;
    if (((ctrlDown) && (e.keyCode == vKey || e.keyCode == cKey || e.keyCode == akey)) || e.keyCode == 17 ||
    event.keyCode == 37 || event.keyCode == 39) return true;

    var reg0Str = '^[0-9]{0,' + numericPlaces + '}(\\.[0-9][0-9]?)?$'; //reg0Str='[0-9]{0,4}\\.?[0-9]{0,2}$'
    var reg0 = new RegExp(reg0Str);
    if (reg0.test(temp)) return true;


    // first replace all non numbers
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
    var reg1 = new RegExp(reg1Str, 'g');
    temp = temp.replace(reg1, '');


    if (allowNegative) {
        // replace extra negative
        var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
        var reg2 = /-/g;
        temp = temp.replace(reg2, '');
        if (hasNegative) temp = '-' + temp;
    }


    if (decimalPlaces != 0) {
        var reg3 = /\./g;
        var reg3Array = reg3.exec(temp);
        if (reg3Array != null) {
            // keep only first occurrence of .
            //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
            var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
            reg3Right = reg3Right.replace(reg3, '');
            reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
            temp = temp.substring(0, reg3Array.index) + '.' + reg3Right;
        }
    }
    if (numericPlaces != 0) {
        var val = temp;


        var points = 0;
        points = val.indexOf(".", points);
        if (points == -1) {
            temp = numericPlaces > 0 ? temp.substring(0, numericPlaces) : temp;
        }
        else {
            var parts = val.split('.');
            if (parts[0].length <= numericPlaces) {
                // return true;
            }
            else {
                var nPart = parts[0];
                nPart = numericPlaces > 0 ? nPart.substring(0, numericPlaces) : nPart;
                temp = nPart + '.' + parts[1];
            }
        }
    }


    obj.value = temp;
    return true;
}


Block Non Numbers
------------------------
function blockNonNumbers(obj, e, allowDecimal, allowNegative) {
    //debugger;
    var ctrlDown = false;
    var ctrlKey = 17, akey = 65, vKey = 86, cKey = 67;

    if (e.keyCode == ctrlKey) ctrlDown = true;
    if (e.keyCode == ctrlKey) ctrlDown = false;
    if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey || e.keyCode == akey)) return true;


    var key = "";
    var isCtrl = false;
    var keychar;
    var reg;


    if (window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey;
    }
    else if (e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }


    if (isNaN(key)) return true;


    keychar = String.fromCharCode(key);


    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl) {
        return true;
    }


    reg = /\d/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;


    return isFirstN || isFirstD || reg.test(keychar);
    // end of  text-box allow numeric and allow 2 decimal points only
}

Wednesday, May 22, 2013

Understanding Action Filters in Asp.Net MVC

The goal of this tutorial is to explain action filters. An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed. The ASP.NET MVC framework includes several action filters:

  • OutputCache – This action filter caches the output of a controller action for a specified amount of time.
  • HandleError – This action filter handles errors raised when a controller action executes.
  • Authorize – This action filter enables you to restrict access to a particular user or role.
You also can create your own custom action filters. For example, you might want to create a custom action filter in order to implement a custom authentication system. Or, you might want to create an action filter that modifies the view data returned by a controller action.
In this tutorial, you learn how to build an action filter from the ground up. We create a Log action filter that logs different stages of the processing of an action to the Visual Studio Output window.

Using an Action Filter

An action filter is an attribute. You can apply most action filters to either an individual controller action or an entire controller.
For example, the Data controller in Listing 1 exposes an action named Index() that returns the current time. This action is decorated with the OutputCache action filter. This filter causes the value returned by the action to be cached for 10 seconds.
Listing 1 – Controllers\DataController.cs
using System;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
     public class DataController : Controller
     {
          [OutputCache(Duration=10)]
          public string Index()
          {
               return DateTime.Now.ToString("T");

          }
     }
}
        
If you repeatedly invoke the Index() action by entering the URL /Data/Index into the address bar of your browser and hitting the Refresh button multiple times, then you will see the same time for 10 seconds. The output of the Index() action is cached for 10 seconds (see Figure 1).
Figure 01: Cached time (Click to view full-size image)
In Listing 1, a single action filter – the OutputCache action filter – is applied to the Index() method. If you need, you can apply multiple action filters to the same action. For example, you might want to apply both the OutputCache and HandleError action filters to the same action.
In Listing 1, the OutputCache action filter is applied to the Index() action. You also could apply this attribute to the DataController class itself. In that case, the result returned by any action exposed by the controller would be cached for 10 seconds.

The Different Types of Filters

The ASP.NET MVC framework supports four different types of filters:
  1. Authorization filters – Implements the IAuthorizationFilter attribute.
  2. Action filters – Implements the IActionFilter attribute.
  3. Result filters – Implements the IResultFilter attribute.
  4. Exception filters – Implements the IExceptionFilter attribute.
Filters are executed in the order listed above. For example, authorization filters are always executed before action filters and exception filters are always executed after every other type of filter.
Authorization filters are used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter.
Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns.
Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.
Each different type of filter is executed in a particular order. If you want to control the order in which filters of the same type are executed then you can set a filter's Order property.
The base class for all action filters is the System.Web.Mvc.FilterAttribute class. If you want to implement a particular type of filter, then you need to create a class that inherits from the base Filter class and implements one or more of the IAuthorizationFilter, IActionFilter, IResultFilter, or ExceptionFilter interfaces.

The Base ActionFilterAttribute Class

In order to make it easier for you to implement a custom action filter, the ASP.NET MVC framework includes a base ActionFilterAttribute class. This class implements both the IActionFilter and IResultFilter interfaces and inherits from the Filter class.
The terminology here is not entirely consistent. Technically, a class that inherits from the ActionFilterAttribute class is both an action filter and a result filter. However, in the loose sense, the word action filter is used to refer to any type of filter in the ASP.NET MVC framework.
The base ActionFilterAttribute class has the following methods that you can override:
  • OnActionExecuting – This method is called before a controller action is executed.
  • OnActionExecuted – This method is called after a controller action is executed.
  • OnResultExecuting – This method is called before a controller action result is executed.
  • OnResultExecuted – This method is called after a controller action result is executed.
In the next section, we'll see how you can implement each of these different methods.

Creating a Log Action Filter

In order to illustrate how you can build a custom action filter, we'll create a custom action filter that logs the stages of processing a controller action to the Visual Studio Output window. Our LogActionFilter is contained in Listing 2.
Listing 2 – ActionFilters\LogActionFilter.cs
using System;
using System.Diagnostics;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1.ActionFilters
{
     public class LogActionFilter : ActionFilterAttribute

     {
          public override void OnActionExecuting(ActionExecutingContext filterContext)
          {
               Log("OnActionExecuting", filterContext.RouteData);       
          }

          public override void OnActionExecuted(ActionExecutedContext filterContext)
          {
               Log("OnActionExecuted", filterContext.RouteData);       
          }

          public override void OnResultExecuting(ResultExecutingContext filterContext)
          {
               Log("OnResultExecuting", filterContext.RouteData);       
          }

          public override void OnResultExecuted(ResultExecutedContext filterContext)
          {
               Log("OnResultExecuted", filterContext.RouteData);       
          }


          private void Log(string methodName, RouteData routeData)
          {
               var controllerName = routeData.Values["controller"];
               var actionName = routeData.Values["action"];
               var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
               Debug.WriteLine(message, "Action Filter Log");
          }

     }
}
        
In Listing 2, the OnActionExecuting(), OnActionExecuted(), OnResultExecuting(), and OnResultExecuted() methods all call the Log() method. The name of the method and the current route data is passed to the Log() method. The Log() method writes a message to the Visual Studio Output window (see Figure 2).
Figure 02: Writing to the Visual Studio Output window (Click to view full-size image)
The Home controller in Listing 3 illustrates how you can apply the Log action filter to an entire controller class. Whenever any of the actions exposed by the Home controller are invoked – either the Index() method or the About() method – the stages of processing the action are logged to the Visual Studio Output window.
Listing 3 – Controllers\HomeController.cs
using System.Web.Mvc;
using MvcApplication1.ActionFilters;

namespace MvcApplication1.Controllers
{
     [LogActionFilter]
     public class HomeController : Controller
     {
          public ActionResult Index()
          {
               return View();
          }

          public ActionResult About()
          {

               return View();
          }
     }
}
        

Summary

In this tutorial, you were introduced to ASP.NET MVC action filters. You learned about the four different types of filters: authorization filters, action filters, result filters, and exception filters. You also learned about the base ActionFilterAttribute class.
Finally, you learned how to implement a simple action filter. We created a Log action filter that logs the stages of processing a controller action to the Visual Studio Output window.

Types of ASP.NET MVC 3 Action Results

This will surprise some of you that know me or the company I work for, but not all of our staff are experts with ASP.NET MVC. In fact, I am hoping that the couple who aren’t will read this post and learn a little bit more about the topic.
Since the actions of controllers in MVC are dealt with constantly, I think it is a good place to start. This post is going to briefly describe the different types of results that are available to you in ASP.NET MVC 3. I will show some of the code that makes them work, which should make all of this seem a lot less complicated.
When creating new controllers in ASP.NET MVC 3, they will come with one or more actions by default. This depends on whether you selected a template which includes extras for you. The Empty controller template comes with an Index action with a return value of type ActionResult.

ActionResult

The action result is a very generic return value for an action. This is because it is the abstract base class for other types of actions. It is actually a very simple class having only one method that needs implementing.
public abstract class ActionResult
{
    public abstract void 
        ExecuteResult(ControllerContext context);
}
Inheriting from the ActionResult are the following classes:
  • ContentResult
  • EmptyResult
  • FileResult
  • HttpStatusCodeResult
  • JavaScriptResult
  • RedirectResult
  • RedirectToRouteResult
  • ViewResultBase
These are the classes that inherit from ActionResult indirectly:
  • FileContentResult
  • FilePathResult
  • FileStreamResult
  • HttpNotFoundResult
  • HttpUnauthorizedResult
  • PartialViewResult
  • ViewResult

ViewResultBase, ViewResult, and PartialViewResult

The ViewResult is the most common concrete type you will be returning as a controller action. It has an abstract base class called ViewResultBase, which it shares with PartialViewResult.
It is in the ViewResultBase abstract base class that we get access to all of our familiar data objects like: TempData, ViewData, and ViewBag.
PartialViews are not common as action results. PartialViews are not the primary thing being displayed to the user, that is the View. The partial view is usually a widget or something else on the page. It’s usually not the primary content the user sees.
This is the common return syntax, and it means that you’re returning a ViewResult.
return View();
That is actually a call to the base Controller.View method, which is just going to call through with some defaults.
protected internal ViewResult View()
{
    return View(null, null, null); 
}
 
The beauty of ASP.NET MVC is actually in its simplicity though, because all that really did was create our ViewResult for us. If we take a look at the method that is being called you can see that we’re just taking a little shortcut and keeping our action clean of this code we would otherwise repeat every time we wanted a ViewResult.
protected internal virtual ViewResult View(
    string viewName, string masterName, object model) 
{
    if (model != null) 
    { 
        ViewData.Model = model; 
    }
 
    return new ViewResult 
    {
        ViewName = viewName,
        MasterName = masterName,
        ViewData = ViewData, 
        TempData = TempData
    }; 
} 
Notice how simple that really is. All it did was put the model data in if we specified it, give the ViewResult the Controller properties that we set already, and assign the viewName and masterName.
Keep in mind, that we already saw that the abstract method in the ActionResult was the ExecuteResult method. The last two things to look at with the ViewResultBase are the ExecuteResult method and its abstract method FindView, which is being implemented by ViewResult and PartialViewResult.
public override void ExecuteResult(
    ControllerContext context)
{
    if (context == null) 
    { 
        throw new ArgumentNullException("context"); 
    }
    if (String.IsNullOrEmpty(ViewName)) 
    { 
        ViewName = context.RouteData
            .GetRequiredString("action");
    }

    ViewEngineResult result = null; 

    if (View == null) 
    { 
        result = FindView(context); 
        View = result.View;
    } 

    TextWriter writer = context.HttpContext.Response.Output;
    ViewContext viewContext = new ViewContext(
        context, View, ViewData, TempData, writer);
    View.Render(viewContext, writer); 

    if (result != null) 
    { 
        result.ViewEngine.ReleaseView(context, View); 
    }
} 
This method is also not very complicated. It checks to make sure we have context, and then if we don’t have the ViewName then we get that information from the RouteData. Remember in MVC that the name of action is included in the RouteData, so we can use that as the default view name. This means that in the Index action, if we just call View(), it will give us a ViewName of “Index”.
We then get the view we’re looking for by calling the FindView abstract method, which means we’re calling through to either ViewResult and PartialViewResult. Those I am not going to get into the guts of, but each one is going to try to find the correct view based on the name using its collection of ViewEngines.
Once we have the view, we are able to tell it to render itself using the context and the TextWriter we give to it.
That’s all there is to a ViewResult.

ContentResult

The content result lets you define whatever content you wish to return. You can specify the content type, the encoding, and the content. This gives you control to have the system give whatever response you want. This is a good result to use when you need a lot of control over what you’re returning and it’s not one of the standards.
Its ExecuteResult override is extremely simple.
public override void ExecuteResult(ControllerContext context) 
{ 
    if (context == null) 
    {
        throw new ArgumentNullException("context"); 
    } 

    HttpResponseBase response = context.HttpContext.Response; 

    if (!String.IsNullOrEmpty(ContentType)) 
    {
        response.ContentType = ContentType;
    } 
    if (ContentEncoding != null) 
    {
        response.ContentEncoding = ContentEncoding; 
    } 
    if (Content != null) 
    {
        response.Write(Content); 
    }
}
It just puts what you specified directly into the response.

EmptyResult

There is no simpler result than the EmptyResult. All it does is override the ExecuteResult method and since that method is void, the method is empty.
I really don’t think I need that code snippet for this one.

FileResult, FileStreamResult, FilePathResult, and FileContentResult

If you want specific actions to send files as the response, then the FileResult is for you. Sadly, the FileResult is abstract, so you’ll need to use one of the inheriting classes instead. Each of these actually just overrides the WriteFile method for the abstract FileResult class.
If you want to just send the contents of the file back with the array of bytes for the file, then you want the FileContentResult. It uses the response’s OutputStream and writes those bytes directly into the stream sending it down to the user.
If you want to transmit the file using its name, you can use FilePathResult, which will call through a whole bunch of layers finally down to the HttpResponse. Once there it is going to create a new FileStream for your file and write the stream to the response allowing the file to be accessed from your action.
If you’ve already got a stream you can use the FileStreamResult, which will read all of the data from your stream and then write it into the OutputStream to be send back in the response.
These really aren’t all that complicated, but if you want to have control over the file downloads in your application, this is a great way to do it. These give you the power to put any code you want in your action before you give back the FileResult.

HttpStatusCodeResult

The HttpStatusCodeResult is as simple as the ContentResult. In fact, the two are quite similar since they both just directly modify the response object.
This one lets you return any StatusCode you want and you can include a StatusDescription for specifics.
public override void ExecuteResult(ControllerContext context)
{ 
    if (context == null)
    {
        throw new ArgumentNullException("context"); 
    } 

    context.HttpContext.Response.StatusCode = StatusCode; 
    if (StatusDescription != null)
    {
        context.HttpContext.Response
            .StatusDescription = StatusDescription;
    }
} 
See how simple that is? It’s basically just two lines of code with some null checking included.

HttpNotFoundResult and HttpUnauthorizedResult

These two results are actually just implementing the HttpStatusCodeResult, which means that they are very simple and just set the StatusCode to 404 for the HttpNotFoundResult and 401 for the HttpUnauthorizedResult.

JavaScriptResult

About as simple as plenty of the others, this is just a quick way of getting JavaScript returned from a action. It’s similar to the ContentResult, but it has the ContentType hardcoded to “application/x-javascript” and just writes out the Script property.
public override void ExecuteResult(ControllerContext context)
{
    if (context == null)
    {
        throw new ArgumentNullException("context");
    } 

    HttpResponseBase response = context.HttpContext.Response; 
    response.ContentType = "application/x-javascript"; 

    if (Script != null)
    { 
        response.Write(Script);
    }
}

JsonResult

This one is a bit more complex, but still not very. It also has hardcoded its ContentType, but what makes it a bit more complex is that it uses a hardcoded JavaScriptSerializer to serialize the JSON data before writing it directly to the response.
public override void ExecuteResult(ControllerContext context)
{ 
    if (context == null)
    { 
        throw new ArgumentNullException("context");
    } 
    if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
        String.Equals(context.HttpContext.Request.HttpMethod, 
            "GET", StringComparison.OrdinalIgnoreCase)) 
    {
        throw new InvalidOperationException(
            MvcResources.JsonRequest_GetNotAllowed);
    } 

    HttpResponseBase response = context.HttpContext.Response; 
 
    if (!String.IsNullOrEmpty(ContentType)) {
        response.ContentType = ContentType; 
    }
    else {
        response.ContentType = "application/json";
    } 
    if (ContentEncoding != null) {
        response.ContentEncoding = ContentEncoding; 
    } 
    if (Data != null) {
        JavaScriptSerializer serializer = 
            new JavaScriptSerializer(); 
        response.Write(serializer.Serialize(Data));
    }
}

RedirectResult and RedirectToRouteResult

These to are a little bit more complex, but both are ways of redirecting. Each one can either be a permanent or temporary redirect and they both just use the Redirect methods on the Response object.
For redirecting to a route, it is going to generate a URL to the route using the UrlHelper’s GenerateUrl method. For the RedirectResult it is instead going to use the UrlHelpers GenerateContentUrl method.
Either of these two are useful, and both will maintain your TempData if you need to pass something along with the redirect, all you have to do is put it in TempData.

Conclusion

I hope you’ve learned that the results of actions in MVC are not actually very complicated, but there is a lot you can do with them. You’re not being forced into just displaying views. You have a lot more control than that. None of them were that complicated were they? The code under the hood is not always complicated, so it’s worth taking a look from time to time. If you examine how something is working, it’s often far easier to use it.

Change Date object to any type of Date Format in MVC Controller

Java Script
----------------------
Date.prototype.customFormat = function(formatString) {
    var YYYY, YY, MMMM, MMM, MM, M, DDDD, DDD, DD, D, hhh, hh, h, mm, m, ss, s, ampm, AMPM, dMod, th;
    var dateObject = this;
    YY = ((YYYY = dateObject.getFullYear()) + "").slice(-2);
    MM = (M = dateObject.getMonth() + 1) < 10 ? ('0' + M) : M;
    MMM = (MMMM = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][M - 1]).substring(0, 3);
    DD = (D = dateObject.getDate()) < 10 ? ('0' + D) : D;
    DDD = (DDDD = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][dateObject.getDay()]).substring(0, 3);
    th = (D >= 10 && D <= 20) ? 'th' : ((dMod = D % 10) == 1) ? 'st' : (dMod == 2) ? 'nd' : (dMod == 3) ? 'rd' : 'th';
    formatString = formatString.replace("#YYYY#", YYYY).replace("#YY#", YY).replace("#MMMM#", MMMM).replace("#MMM#", MMM).replace("#MM#", MM).replace("#M#", M).replace("#DDDD#", DDDD).replace("#DDD#", DDD).replace("#DD#", DD).replace("#D#", D).replace("#th#", th);
    h = (hhh = dateObject.getHours());
    if (h == 0) h = 24;
    if (h > 12) h -= 12;
    hh = h < 10 ? ('0' + h) : h;
    AMPM = (ampm = hhh < 12 ? 'am' : 'pm').toUpperCase();
    mm = (m = dateObject.getMinutes()) < 10 ? ('0' + m) : m;
    ss = (s = dateObject.getSeconds()) < 10 ? ('0' + s) : s;
    return formatString.replace("#hhh#", hhh).replace("#hh#", hh).replace("#h#", h).replace("#mm#", mm).replace("#m#", m).replace("#ss#", ss).replace("#s#", s).replace("#ampm#", ampm).replace("#AMPM#", AMPM);
};

How to Create Cursor

declare @tempt table
(
ID int null,
Name varchar(100) null
)
DECLARE @vendor_id int, @vendor_name nvarchar(50),
    @message varchar(80), @product nvarchar(50);
PRINT '-------- Vendor Products Report --------';
-- Declare Cursor – untill it deallocate
-- You Con’t declare another cursor with same name.
DECLARE vendor_cursor CURSOR FOR
SELECT ID,Ag_Fname
from AgentMaster
OPEN vendor_cursor
FETCH NEXT FROM vendor_cursor
INTO @vendor_id, @vendor_name
WHILE @@FETCH_STATUS = 0
BEGIN
   
    SELECT @message = '----- Vendor: ' +
        @vendor_name
    PRINT @message
    insert INTO @tempt values (@vendor_id, @vendor_name)
   
    FETCH NEXT FROM vendor_cursor
    INTO @vendor_id, @vendor_name
END
CLOSE vendor_cursor;
select * from @tempt
-- Deallocate Cursor
DEALLOCATE vendor_cursor;

How To Create A Trigger.

Trigger is procedural code that is automatically executed in response to certain events on a specific table in a database. Triggers can restrict access to specific data, perform logging, or audit data modifications.
Triggers are of 3 types in SQL Server 2005:

1. DML Triggers
   - AFTER Triggers
   - INSTEAD OF Triggers { INSERT, UPDATE, and DELETE }
2. DDL Triggers {if any schema change.}
3. CLR Triggers
Create trigger Delete_TrigerName
on ReferanceTable
for Delete
as
--Checking for Table exist.
--if Table not exist then create a table with same schema of operation table
if NOT EXISTS(SELECT * FROM information_schema.tables
                              WHERE TABLE_CATALOG = 'DATABASE-NAME'
                              AND table_name = 'Backup-TABLE-NAME')
begin
-- Copy full table with creating table of copied table schema                      
     select * into  Backup-TABLE-NAME from deleted
--Set Identity column Off. Otherwise we will not able to track the                                                                                                                                previous position of table.
     SET IDENTITY_INSERT [Backup-TABLE-NAME ] off
end
else
begin
       INSERT INTO Backup-TABLE-NAME ([Column1],[ Column2],[ Column3])
       SELECT [Column1],[ Column2],[ Column3]
       FROM deleted
end
--select * from Backup-TABLE-NAME
--select * from AgentMaster
--delete from AgentMaster where Ag_ApplNo=22

Pan Number format and Duplication entry validation in KendoUi

Checking from database using json and Controler's action where controler is Validation and Action is CheckPanNo . Then we check format using test function. and error message set to messages section of  kendoValidator function.

Java Script

 

///Pan No Duplication checking
        var validatable = $("#Pan").kendoValidator({
            onfocusout: true,
            onkeyup: true,
            rules: {
                PanNo: function (input) {
                    $.post("/Validation/CheckPanNo", { PanNo: $("#Pan").val() }, function (data) { b1 = data; })
                    return b1;
                },
                PanFormat: function (input) {
                    // return validatePanCard('Pan');
                    var value = input.val();
                    var regex1 = /^[A-Z]{5}\d{4}[A-Z]{1}$/;
                    if (!regex1.test(value) || value.length != 10) {
                        return false;
                    }
                    return true;
                }
               
            },
            messages: {
                PanNo: "Already Exist",
                PanFormat: "Not a currect format"
            }
        }).data("kendoValidator");

 Action

 

[HttpPost]
        public JsonResult CheckPanNo(string PanNo)
        {
            bool IsOk = projectRepository.CheckPanNumber(PanNo);
            return Json(IsOk, JsonRequestBehavior.AllowGet);
        }