Monday, May 19, 2014

What is SOAP and RESTFul Webservice

SOAP
Simple Object Access Protocol (SOAP) standard an XML language defining a message architecture and message formats, is used by Web services it contain a description of the operations. WSDL is an XML-based language for describing Web services and how to access them. will run on SMTP,HTTP,FTP etc. Requires middleware support, well defined mechanisam to define services like WSDL+XSD, WS-Policy SOAP will return XML based data
REST  Representational State Transfer (RESTful) web services. they are second generation Web Services. RESTful web services, communicate via HTTP than SOAP-based services and do not require XML messages or WSDL service-API definitions. for REST no middleware is required only HTTP support is needed.WADL Standard, REST can return XML, plain text, JSON, HTML etc

Friday, May 16, 2014

3 Tier Applications Model


Enumeration

    An Enumeration is used to store pre-defined values.

It is not a data structure. An Enumeration is derived from  System.Enum structure.

public enum  MyValues  // : int
{
Value1, // 0
Value2 = 100,
Value3, // 101
Value4, // 102
}

Default Data Type of an enum is 'int'.

public enum  MyColors : short {
Red, // 0
Green, // 1
Yellow, // 2
Blue // 3
}
------------------------------------------------------------------------------------------------
Data Types supported in an enumeration are:
byte, sbyte,
short, ushort,
int[default], uint,
long, ulong.

Char type is NOT supported.

MyValues.Value1 // Value1
(int) MyValues.Value1 // 0

MyColors.Red // Red
(short) MyColors.Red // 0


Enumeration in .NET Class Library:

TextBoxMode  enum // TextBox
RepeatDirection  enum // DataList, RadioButtonList, CheckBoxList

SqlDbType  enum
CommandType  enum
CommandBehavior  enum

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

if((short)MyColors.Red == 0){
LblMsg.ForeColor = Color.Red;
}

Wednesday, May 14, 2014

convert JSON Date to JavaScript date in Javascripts




new Date(parseInt(JSONDateFromServerSide.substr(6))
Let's use the above code in a simple demo and then we will discuss what's the magic in the above line. Below is the 

sample code for the demo.  this JSON date will converted to JavaScript date and different date methods are then applied to this JavaScript date.


<html>
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">

        // Add the page method call as an onclick handler for the div. 
        $(document).ready(function () {
            debugger;
            //Date fetched directly what is given from server side
            var dateAsFromServerSide = "/Date(1418322600000)/";

            //Now let's convert it to js format
            //Example: Fri Dec 03 2010 16:37:32 GMT+0530 (India Standard Time)
            var parsedDate = new Date(parseInt(dateAsFromServerSide.substr(6)));

            var jsDate = new Date(parsedDate); //Date object

            //Play with jsDate properties getDate(), getDay() etc

            var html = 'dateAsFromServerSide:' + dateAsFromServerSide +
            '<br/>' + 'parsedDate: ' + parsedDate +
            '<br/>' + 'jsDate.getDay(): ' + jsDate.getDay() +
            '<br/>' + 'jsDate.getDate(): ' + jsDate.getDate() +
            '<br/>' + 'jsDate.getFullYear(): ' + jsDate.getFullYear() +
            '<br/>' + 'jsDate.getHours(): ' + jsDate.getHours() +
            '<br/>' + 'jsDate.getMilliseconds(): ' + jsDate.getMilliseconds() +
            '<br/>' + 'jsDate.getMinutes(): ' + jsDate.getMinutes() +
            '<br/>' + 'jsDate.getMonth(): ' + jsDate.getMonth() +
            '<br/>' + 'jsDate.getSeconds(): ' + jsDate.getSeconds() +
            '<br/>' + 'jsDate.getTime():' + jsDate.getTime() +
            '<br/>' + 'jsDate.getTimezoneOffset(): ' + jsDate.getTimezoneOffset() +
            '<br/>' + 'jsDate.getUTCDate(): ' + jsDate.getUTCDate() +
            '<br/>' + 'jsDate.getUTCDay(): ' + jsDate.getUTCDay() +
            '<br/>' + 'jsDate.getUTCFullYear(): ' + jsDate.getUTCFullYear() +
            '<br/>' + 'jsDate.getUTCHours(): ' + jsDate.getUTCHours() +
            '<br/>' + 'jsDate.getUTCMilliseconds(): ' + jsDate.getUTCMilliseconds() +
            '<br/>' + 'jsDate.getUTCMinutes(): ' + jsDate.getUTCMinutes() +
            '<br/>' + 'jsDate.getUTCMonth(): ' + jsDate.getUTCMonth() +
            '<br/>' + 'jsDate.getUTCSeconds(): ' + jsDate.getUTCSeconds() +
            '<br/>' + 'jsDate.getYear(): ' + jsDate.getYear();
          
            //Fill html
            $('#divDate').html(html);

        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="divDate">
        </div>
    </form>
</body>

</html>

Output
dateAsFromServerSide:/Date(1418322600000)/
parsedDate: Thu Dec 11 2014 23:59:00 GMT+0529 (India Standard Time)
jsDate.getDay(): 4
jsDate.getDate(): 11
jsDate.getFullYear(): 2014
jsDate.getHours(): 23
jsDate.getMilliseconds(): 0
jsDate.getMinutes(): 59
jsDate.getMonth(): 11
jsDate.getSeconds(): 0
jsDate.getTime():1418322600000
jsDate.getTimezoneOffset(): -329
jsDate.getUTCDate(): 11
jsDate.getUTCDay(): 4
jsDate.getUTCFullYear(): 2014
jsDate.getUTCHours(): 18
jsDate.getUTCMilliseconds(): 0
jsDate.getUTCMinutes(): 30
jsDate.getUTCMonth(): 11
jsDate.getUTCSeconds(): 0
jsDate.getYear(): 114

Angular, Backbone or Ember: Which JavaScript Framework best for you?

Developers use JavaScript for a number of different web applications. If you continue adding more code to make it work in multiple browsers and use cases, it can quickly become a big mess. Hence you’d better use a framework to avoid this.
Frameworks like Angular, Backbone and Ember make your JavaScript code structured and keep it organized. Being all open source, they’re constantly improved by the community. They also save your time as they’re built on top of JQuery, a fast and powerful library that makes some of JavaScript’s complex operations easier to perform and more readable.
However, choosing your JavaScript framework isn’t such easy and could be challenging. Let’s try to understand how Angular, Backbone and Ember are different from each other and what their strengths and weaknesses are.
AngularJS
AngularJS is an open-source web application framework, maintained by Google and community, that assists with creating single-page applications, one-page web applications that only require HTML, CSS, and JavaScript on the client side. Its goal is to augment web applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier.
AngularJS was originally developed in 2009, and it is the oldest of the three frameworks. It also has the largest community. In 2013, Angular was fourth in number of project contributors on GitHub and third in number of stars gain which testifies to its huge popularity. Moreover such well-known companies as Amazon, Google and Nike credit AngularJS as JavaScript framework. There are also a lot of news sites using AngularJS on their front pages, including the Guardian, the Huffington Post, and MSNBC. You may also check https://builtwith.angularjs.org/ to have a look at good examples of Angular apps and experiments.
Pros
  • Ideal for complex “client-side” applications, where the complexity is more in a way “components” of an application interacts with each other than in a way they synchronise and/or interact with backend
  • Very clear separation of concerns
  • Uses concepts that kind of look like the future of HTML/DOM (DOM templates, binding attributes).
Cons
  • A bit complicated to grasp. A lot of new concepts
  • jQuery or another dom parsing framework in directives may be painful to use because of the way angular compiles templates
  • Good for application with a big level of complexity on the client side, but you’ll have to learn a lot of new stuff.
On the whole, AngularJS is a robust and viable framework for building generic web apps. Whether it lives up to the expectations of being the most dominant JS framework for web development is yet to be seen.
Backbone.js
Backbone.js  is a JavaScript library with a RESTful JSON interface and is based on the model–view–presenter (MVP) application design paradigm. Backbone is known for being lightweight, as its only dependency is on one JavaScript library, Underscore.js. It is designed for developing single-page web applications and for keeping various parts of web applications (e.g. multiple clients and the server) synchronized.
Backbone came out in June 2010, and its community is nearly as large as Angular’s. Many popular applications such as Twitter, LinkedIn Mobile and Foursquare use Backbone framework. Also a number of music apps were built with Backbone, including well-known Pandora, Soundcloud and Pitchfork.
The download size of Backbone is very small compared to other frameworks which is its biggest advantage, since it only depends on one JavaScript library instead of several. Moreover, this framework is remarkably hands-off. This means experienced JavaScript developers can quickly get started. However less experienced developers might find themselves writing a lot of “boilerplate” (repetitive) code. If you’re having trouble Backbone has an especially active community rife where you could find free tutorials for getting started with the framework.
If you’re working on a single-page application or widget and you’re comfortable with being a self-starter—Backbone is likely the right choice for you.
Pros
  • Very easy to start with
  • Very small
  • Free to use any templating engine
  • A lot of excellent documentation
  • Good Community Support
  • Very popular (According to Github, Stackoverflow statistics)
  • Very flexible in how you may want to use it
  • Minimalist library
  • Easy to learn
Cons
  • No two way data-binding
  • Dependency on different frameworks like jQuery and Underscore
  • No provision for handling nested views
  • More work required to build large scale applications as compared to Angular or Ember
  • Code can become messy
  • DOM manipulations are left to the developer
  • Performs slower than AngularJS
Ember
Ember.js is an open-source client-side JavaScript web application framework based on the model-view-controller (MVC) software architectural pattern. It allows developers to create scalable single-page applications by incorporating common idioms and best practices into a framework that provides a rich object model, declarative two-way data binding, computed properties, automatically-updating templates powered by Handlebars.js, and a router for managing application state.
Ember is the newest of the three, but it’s already making waves. LivingSocial, Groupon, Zendesk, Discourse and Square are some of the most well-known applications that have adopted Ember. Ember’s creators say it’s easy to see when a site is using Ember because of its loading speed.
At 69K minified and zipped, Ember is the largest framework of the three. Ember’s larger library size partly explains why it’s the largest download of the three Javascript frameworks. Another reason for it is that Ember comes with a lot of built-in support for standard code features.
Ember’s library size and support network are its two greatest strengths, but if you’re only trying to create a small widget or single-page app, it might be overkill for you. If you’re working on a multipage, navigational, long-term project, Ember might be the right choice for you.
Pros
  • Good for long running and complex applications with deep nested view hierarchies
  • Aggregates model data changes and update the DOM late in the RunLoop
  • Well defined models and computed properties
  • Use HandleBars as templating which is flexible
  • Provides auto updating computed properties
  • Test driven
Cons
  • Relatively new framework
  • Steepest learning curve out of the three
  • Payload is the largest out of all three
  • Dependency on jQuery and Handlebars
  • Poor performance as compared to AngularJS
  • Documentation is not very good
  • Two way bindings are not implemented well
As I could see from a number of forums about JavaScript frameworks, many love AngularJS. What about you? Which one framework is your favorite one and why? Please feel free to share your thoughts/experience in the comments below

Monday, May 12, 2014

An error occurred while updating the entries. See the inner exception for details.


this problem will occur if you are passing the null values to the fields in table which are not null
or
update your Entity Framework Data Model 

Difference between WCF and Web API and WCF REST and Web Service

The .Net framework has a number of technologies that allow you to create HTTP services such as Web Service, WCF and now Web API. There are a lot of articles over the internet which may describe to whom you should use. Now a days, you have a lot of choices to build HTTP services on .NET framework. In this article, I would like to share my opinion with you over Web Service, WCF and now Web API. For more information about Web API refers What is Web API and why to use it ?.

Web Service

  • It is based on SOAP and return data in XML form.
  • It support only HTTP protocol.
  • It is not open source but can be consumed by any client that understands xml.
  • It can be hosted only on IIS.

WCF

  • It is also based on SOAP and return data in XML form.
  • It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  • The main issue with WCF is, its tedious and extensive configuration.
  • It is not open source but can be consumed by any client that understands xml.
  • It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

  • To use WCF as WCF Rest service you have to enable webHttpBindings.
  • It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  • To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  • Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
  • It support XML, JSON and ATOM data format.

Web API

  • This is the new framework for building HTTP services with easy and simple way.
  • Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
  • Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
  • It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
  • It can be hosted with in the application or on IIS.
  • It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  • Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API

  • Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
  • Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
  • Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
  • Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

Client Side Validation in ASP .NET MVC using Data Annotation Attributes

Client Side Validation in ASP .NET MVC using Data Annotation Attributes

In this post we will know how to apply client side validation in Asp .Net MVC.
Step : 1 Take a New ASP.NET MVC 4 Web Application
  Now, you will have a structure

Step : 2 Add a class in the Models folder and write the property which you want to show in view.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.ComponentModel.DataAnnotations;
namespace ValidateMvcForm.Models
{
    public class User
    {
        [Required]
        [StringLength(30)]
        public string FirstName { get; set; }
         
        [StringLength(30)]
        public string MiddleName { get; set; }
        [Required]
        [StringLength(30)]
        public string LastName { get; set;}
        [RegularExpression(@"([a-zA-Z0-9][-a-zA-Z0-9_\+\.]*[a-zA-Z0-9])@([a-zA-Z0-9][-a-zA-Z0-9\.]*[a-zA-Z0-9]\.(arpa|root|aero|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|([0-9]{1,3}\.{3}[0-9]{1,3}))")]
        public string EmailAddress { get; set; }
         
    }
}
Step : 3 Now, Add a Controller in the Controller folder, by right click on Controller (folder) --> Add --> Controller and add an Action in this Controller
?
1
2
3
4
public ActionResult Registration()
        {
            return View();
        }
Now, right click on View() and add a View



and add the following code in Controller as well
[HttpPost]
        public ActionResult Registration(Models.User user)
        {
            return View();
        }
Step : 4 In Registration.cshmtl, write the following code


Now, build your application and run.
And when we click on "Submit" button it looks like

So, Form will not post until we don't fill form according to our model.
So, basically for client Side Validation we just need to add the following code
@section scripts{
@Scripts.Render("~/bundles/jqueryval")
}
and add Attributes in Model class.