Friday, April 25, 2014

Custom column in WebGrid MVC4

@model EcommerceNew_pro.Models.ProModel
@{
    ViewBag.Title = "WebGrid with Custom Paging, Sorting";
    WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
    grid.Bind(Model.Customer,
    autoSortAndPage: false,
    rowCount: Model.TotalRows);
}
<script type="text/javascript">
    $(function () {
        $('.edit-mode').hide();
        $('.edit-user, .cancel-user').live('click', function () {
            var tr = $(this).parents('tr:first');
            tr.find('.edit-mode, .display-mode').toggle();
        });

        $('.save-user').live('click', function () {
            var tr = $(this).parents('tr:first');
            var Customername = tr.find("#Customername").val();
            var Address = tr.find("#Address").val();
            var CustomerId = tr.find("#CustomerId").html();
            tr.find("#lblCustomername").text(Customername);
            tr.find("#lblAddress").text(Address);
            tr.find('.edit-mode, .display-mode').toggle();
            var UserModel =
            {
                "CustomerId": CustomerId,
                "Customername": Customername,
                "Address": Address
            };
            $.ajax({
                url: '/User/UpdateUser/',
                data: JSON.stringify(UserModel),
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert(data);
                }
            });

        });
    })
</script>
@grid.GetHtml(

 fillEmptyRows: false,
     tableStyle: "webgrid-table",
        headerStyle: "webgrid-header",
        footerStyle: "webgrid-footer",
        alternatingRowStyle: "webgrid-alternating-row",
        selectedRowStyle: "webgrid-selected-row",
        rowStyle: "webgrid-row-style",
 mode: WebGridPagerModes.All,
 firstText: "<< First",
 previousText: "< Prev",
 nextText: "Next >",
 lastText: "Last >>",
 columns:
        grid.Columns(

 grid.Column("CustomerId", format: @<text><span class="display-mode">@item.CustomerId</span><label
     id="CustomerId" class="edit-mode">@item.CustomerId</label></text>,
                    style: "col1Width" ),
  grid.Column("Customername", "Name", format: @<text> <span class="display-mode">
      <label id="lblCustomername">@item.Customername</label></span>
<input type="text" id="Customername" style="width:100px" value="@item.Customername" class="edit-mode" /></text>, style: "col2Width"),
        grid.Column("Address", "Address", format: @<text><span class="display-mode"><label
            id="lblAddress">@item.Address</label></span>
<input type="text" id="Address" style="width:100px" value="@item.Address" class="edit-mode" /></text>, style: "col2Width"),

 grid.Column("Action", format: @<text>
<button class="edit-user display-mode">
    Edit</button>
<button class="save-user edit-mode">
    Save</button>
<button class="cancel-user edit-mode">
    Cancel</button>
</text>,  style: "col3Width" , canSort: false)
))


<style type="text/css">
    .edit-mode
    {
    }
    .edit-user
    {
    }
    .edit-user display-mode
    {
    }
    .save-user edit-mode
    {
    }
    .display-mode
    {
    }
    .cancel-user
    {
    }
    .webgrid-table
    {
        font-family: Arial,Helvetica,sans-serif;
        font-size: 14px;
        font-weight: normal;
        width: 650px;
        display: table;
        border-collapse: collapse;
        border: solid px #C5C5C5;
        background-color: white;
    }
    .webgrid-table td, th
    {
        border: 1px solid #C5C5C5;
        padding: 3px 7px 2px;
    }
    .webgrid-header, .webgrid-header a
    {
        background-color: #E3E3E3;
        color: black;
        text-align: left;
        text-decoration: none;
    }
    .webgrid-footer
    {
    }
    .webgrid-row-style
    {
        padding: 3px 7px 2px;
    }
    .webgrid-alternating-row
    {
        background-color: #F5F5F5;
        padding: 3px 7px 2px;
    }
    .col1Width
    {
        width: 50px;
    }
    .col2Width
    {
        width: 200px;
    } .col3Width
    {
        width:300px;
    }
</style>

Tuesday, April 22, 2014

How to show message and redirect to other pages on page loads in asp .net?

StringBuilder strScript = new StringBuilder();
            strScript.Append("<script language=JavaScript>");
            strScript.Append("alert('Some of the product(s) in this Order are not available now. Click OK to continue this order without these product(s)?'); location.href='Home/index'</script>");
            ClientScript.RegisterStartupScript(this.GetType(), "Pop", strScript.ToString());

Monday, April 21, 2014

Top 10 Time consuming t-sql queries in sql server

SELECT TOP 10 SQL_Query = TEXT
    , stat.total_elapsed_time/1000000 as TimeTakenInSecs
    , last_execution_time
FROM sys.dm_exec_query_stats stat
    cross apply
    (
        SELECT dbid , text FROM sys.dm_exec_sql_text(sql_handle)
    ) sqltext
WHERE DB_NAME(dbid) = 'STVLIVE_DB'
ORDER BY total_elapsed_time desc

How to make mackup for all database?

CREATE PROCEDURE dbo.BackUpAllDatabases
( @BackUp_Path VARCHAR(300) )
AS/* -- Comments -- *Created and Licenced to dotnetbites.comThis procedure would backup all the databases that are online to the
@BackUp_Path specified by the developer or DBA*/
BEGIN
DECLARE @DBName VARCHAR(100)
, @fileName VARCHAR(256)
, @Count INT
, @Index INT
DECLARE @Databases TABLE(ID INT IDENTITY, DBName VARCHAR(100)) INSERT INTO @Databases(DBName)
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb')
AND DATABASEPROPERTYEX ([Name],'Status') = 'online'
SELECT @Index = 1, @Count = COUNT(*) FROM @Databases
WHILE @Index <= @Count
BEGIN
SELECT @DBName = DBName FROM @Databases
WHERE ID = @Index
SET @fileName = @BackUp_Path + '/' + @DBName + '_'
SET @fileName =  @fileName + CONVERT(VARCHAR(20),GETDATE(),112) + '.BAK'
BACKUP DATABASE @DBName TO DISK = @fileName
SET @Index = @Index + 1
END
END





exec  BackUpAllDatabases 'D:\bbbb'

C# number to words

public string ConvertToWords(int Amount)
{
    string words = "";
    var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", 
"twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
    var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
    
    if (Amount == 0)
        return "zero";

    if (Amount < 0)
        return "minus " + ConvertToWords(Math.Abs(Amount));            

   
    if ((Amount / 10000000) > 0)
    {
        words += ConvertToWords(Amount / 10000000) + " crore ";
        Amount %= 10000000;
    }

    if ((Amount / 100000) > 0)
    {
        words += ConvertToWords(Amount / 100000) + " lakh ";
        Amount %= 100000;
    }           

    if ((Amount / 1000) > 0)
    {
        words += ConvertToWords(Amount / 1000) + " thousand ";
        Amount %= 1000;
    }

    if ((Amount / 100) > 0)
    {
        words += ConvertToWords(Amount / 100) + " hundred ";
        Amount %= 100;
    }

    if (Amount > 0)
    {
        if (words != "")
            words += "and ";
        

        if (Amount < 20)
            words += unitsMap[Amount];
        else
        {
            words += tensMap[Amount / 10];
            if ((Amount % 10) > 0)
                words += " " + unitsMap[Amount % 10];
        }
    }
    return words;
}

Identify user who modified the table recently

DECLARE @Filename VARCHAR(500)
SELECT @FileName = SUBSTRING(path, 0, LEN(path)-CHARINDEX('\', REVERSE(path))+1) + '\Log.trc'
FROM sys.traces
WHERE is_default = 1;
--SELECT @FileName AS [Log Trace File Name]
SELECT gt.HostName
    , gt.ApplicationName
    , gt.DatabaseName
    , gt.LoginName
    , gt.SPID
    , gt.EventClass
    , te.Name AS EventName
    , gt.TEXTData
    , gt.StartTime
    , gt.EndTime
    , gt.ObjectName 
FROM [fn_trace_gettable](@filename, DEFAULT) gt
    JOIN sys.trace_events te
        ON gt.EventClass = te.trace_event_id
WHERE EventClass = 164
ORDER BY StartTime DESC;

Friday, April 18, 2014

Shopping cart in MVC

1:Make a database in SQL
USE [Ecommerce_DB]
GO
/****** Object:  Table [dbo].[TblProduct]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TblProduct](
[productid] [int] IDENTITY(1,1) NOT NULL,
[productcode] [varchar](250) NULL,
[Productname] [varchar](250) NULL,
[UnitPrice] [decimal](12, 2) NULL,
[StockQuantity] [int] NULL,
[CategoryId] [int] NULL,
[Images] [varchar](250) NULL,
PRIMARY KEY CLUSTERED
(
[productid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TblorderDetails]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TblorderDetails](
[OrderDetailsid] [int] IDENTITY(1,1) NOT NULL,
[Customerid] [varchar](250) NULL,
[OrderId] [int] NULL,
[ProductCode] [varchar](250) NULL,
[UnitPrice] [decimal](12, 2) NULL,
[Quantity] [int] NULL,
[TotalPrice] [decimal](12, 2) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Tblorder]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Tblorder](
[OrderId] [int] IDENTITY(1,1) NOT NULL,
[Customerid] [varchar](250) NULL,
[TotalPrice] [decimal](12, 2) NULL,
PRIMARY KEY CLUSTERED
(
[OrderId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[TblCustomer]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[TblCustomer](
[CustomerId] [int] IDENTITY(1,1) NOT NULL,
[Customername] [varchar](250) NULL,
[Country] [varchar](250) NULL,
[address] [varchar](250) NULL,
[UserName] [varchar](250) NULL,
[Password] [varchar](250) NULL,
PRIMARY KEY CLUSTERED
(
[CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Tblcategory]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Tblcategory](
[CategoryId] [int] IDENTITY(1,1) NOT NULL,
[SubcategoryId] [int] NULL,
[categoryname] [varchar](250) NULL,
PRIMARY KEY CLUSTERED
(
[CategoryId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[Tblcart]    Script Date: 04/18/2014 17:19:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Tblcart](
[Cartid] [int] IDENTITY(1,1) NOT NULL,
[Customerid] [varchar](250) NULL,
[ProductCode] [varchar](250) NULL,
[UnitPrice] [decimal](12, 2) NULL,
[Quantity] [int] NULL,
[TotalPrice] [decimal](12, 2) NULL,
PRIMARY KEY CLUSTERED
(
[Cartid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

2:Create Model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Ecommerce1_Pr.Models
{


    public class Cart
    {
        public string Customerid { get; set; }
        public string ProductCode { get; set; }
        public decimal UnitPrice { get; set; }
        public int Quantity { get; set; }
        public decimal TotalPrice { get; set; }
    }
    public class Products
    {
        public int ProductID;
        public string ProductName;
        public string ProductCode;
        public decimal Price;
        public string ProductImage;
        public int CategoryId;
        public int Quantity;
    }
    public partial class ShoppingCart
    {
        Ecommerce_DBEntities storeDB = new Ecommerce_DBEntities();
        string ShoppingCartId { get; set; }
        public const string CartSessionKey = "CartId";
        public static ShoppingCart GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCart();
            cart.ShoppingCartId = cart.GetCartId(context);
            return cart;
        }
        // Helper method to simplify shopping cart calls
        public static ShoppingCart GetCart(Controller controller)
        {
            return GetCart(controller.HttpContext);
        }
        public void AddToCart(Products prmod)
        {
            // Get the matching cart and album instances
            var cartItem = storeDB.Tblcarts.SingleOrDefault(
                c => c.Customerid == ShoppingCartId
                && c.ProductCode == prmod.ProductCode);
            if (cartItem == null)
            {
                Tblcart c = new Tblcart();
                c.ProductCode = prmod.ProductCode;
                c.Customerid = ShoppingCartId;
                c.Quantity = prmod.Quantity;
                c.UnitPrice = prmod.Price;
                c.TotalPrice = prmod.Price * prmod.Quantity;
                storeDB.Tblcarts.Add(c);
            }
            else
            {
                // If the item does exist in the cart,
                // then add one to the quantity
                cartItem.Quantity = cartItem.Quantity + prmod.Quantity;
            }
            // Save changes
            storeDB.SaveChanges();
        }

        // We're using HttpContextBase to allow access to cookies.
        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] =
                        context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class
                    Guid tempCartId = Guid.NewGuid();
                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }
        public List<Cart> GetBasket(ShoppingCart  c1)
        {
            List<Cart> cc = new List<Cart>();
   
            var c = storeDB.Tblcarts.Where(p => p.Customerid == c1.ShoppingCartId);
            foreach (var ss in c.AsEnumerable<Tblcart>())
            {
                cc.Add(new Cart { Customerid = ss.Customerid, ProductCode = ss.ProductCode, UnitPrice = (decimal)ss.UnitPrice, Quantity = (int)ss.Quantity, TotalPrice = (decimal)ss.TotalPrice });


            }
            return cc;
        }
    }
}



3:Create Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ecommerce1_Pr.Models;
using System.Web.UI.HtmlControls;


namespace Ecommerce1_Pr.Controllers
{
    public class HomeController : Controller
    {      
        Ecommerce_DBEntities storeDB = new Ecommerce_DBEntities();
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ProductCategory()
        {
            var ProductCategory = storeDB.Tblcategories;
            return View(ProductCategory);
        }
        public ActionResult Product(int id)
        {
            var Product = storeDB.TblProducts.Where(p => p.CategoryId == id);
            return View(Product);
        }
        [HttpPost]
        public ActionResult AddToCart(string PrCode, string Pcatid, string txtQuantity)
        {
            TblProduct p = storeDB.TblProducts.FirstOrDefault(ap => ap.productcode == PrCode);
            Products p1 = new Products();
            p1.ProductID = p.productid;
            p1.ProductCode = p.productcode;
            p1.ProductName = p.Productname;
            p1.Price = (Decimal)p.UnitPrice;
            p1.ProductImage = p.Images;
            p1.CategoryId = (int)p.CategoryId;
            p1.Quantity = Convert.ToInt32(txtQuantity);
                     
            var cart =Ecommerce1_Pr.Models.ShoppingCart.GetCart(this.HttpContext);
            cart.AddToCart(p1);
            return RedirectToAction("Product", "Home", new { id = Pcatid });
        }
        public ActionResult Productdetails(int id)
        {
            TblProduct p = storeDB.TblProducts.FirstOrDefault(ap => ap.productid == id);
            Products p1 = new Products();
            p1.ProductID = p.productid;
            p1.ProductCode = p.productcode;
            p1.ProductName = p.Productname;
            p1.Price = (Decimal)p.UnitPrice;
            p1.ProductImage = p.Images;
            p1.CategoryId = (int)p.CategoryId;
            return View(p1);
        }
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            LoginModel ln = new LoginModel();
            ViewBag.ReturnUrl = returnUrl;
            return View(ln);
        }    
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (CheckLogin(model))
                {
                    Response.Redirect("index");
                }
            }
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }
        public bool CheckLogin(LoginModel ln)
        {
            Session["CustomerId"] = "0";
            var c = storeDB.TblCustomers.Where(u => u.UserName == ln.UserName);
            if (c != null)
            {
                Session["CustomerId"] = ln.UserName;
                return true;
            }
            else { return false; }
        }
        public ActionResult ShoppingCart()
        {
            var cart = Ecommerce1_Pr.Models.ShoppingCart.GetCart(this.HttpContext);

            List<Cart> cc = null;
            ShoppingCart sc = new Models.ShoppingCart();
            cc = sc.GetBasket(cart);
            return View(cc);
        }
       
    }
}

Sunday, April 13, 2014

Paging & Sorting in MVC 4 with Grid.

1:Create model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    public class ProModel
    {
        public int TotalRows { get; set; }
        public IEnumerable<TblCustomer> Customer { get; set; }
        public int PageSize { get; set; }
    }
    public class ModelServices : IDisposable
    {
        private readonly tst_dbEntities entities = new tst_dbEntities();

        public IEnumerable<TblCustomer> GetCustomerPage(int pageNumber, int pageSize, string sort, bool Dir)
        {
            if (pageNumber < 1)
                pageNumber = 1;

            if (sort == "name")
                return entities.TblCustomers.OrderByDescending(x => x.Customername)
                .Skip((pageNumber - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            else
                return entities.TblCustomers.OrderBy(x => x.CustomerId)
                .Skip((pageNumber - 1) * pageSize)
                .Take(pageSize)
                .ToList();
        }
        public int CountCustomer()
        {
            return entities.TblCustomers.Count();
        }

        public void Dispose()
        {
            entities.Dispose();
        }
    }
    public static class SortExtension
    {

    }
}

2:Create Controller

 public class HomeController : Controller
    {
        ModelServices mobjModel = new ModelServices();

        public ActionResult WebGridCustomPaging(int page = 1, string sort = "custid", string sortDir = "ASC")
        {
            const int pageSize = 3;
            var totalRows = mobjModel.CountCustomer();

            bool Dir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? true : false;

            var customer = mobjModel.GetCustomerPage(page, pageSize, sort, Dir);
            var data = new ProModel()
            {
                TotalRows = totalRows,
                PageSize = pageSize,
                Customer = customer
            };
            return View(data);
        }
}

3:Create View
@model MvcApplication1.Models.ProModel
@{
 ViewBag.Title = "WebGrid with Custom Paging, Sorting";
 WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
 grid.Bind(Model.Customer,
 autoSortAndPage: false,
 rowCount: Model.TotalRows); 
}
 
@grid.GetHtml(
 fillEmptyRows: false,
 alternatingRowStyle: "alternate-row",
 headerStyle: "grid-header",
 footerStyle: "grid-footer",
 mode: WebGridPagerModes.All,
 firstText: "<< First",
 previousText: "< Prev",
 nextText: "Next >",
 lastText: "Last >>",
 columns: new[] {
 grid.Column("CustomerId",header: "ID", canSort: false),
 grid.Column("Customername"),
 grid.Column("Address"),
 grid.Column("City",header: "City")
 }
)

Wednesday, April 9, 2014

Difference between ASP.Net Web Service and WCF service

Sr. No
Features
ASP.net Web Service
WCF Service
1
File Format/Extension
ASP.net web services uses .asmx as a file extension.
WCF web service uses .svc as a file extension.
2
Hosting
ASP.net Web service can be hosted in IIS. As well as ASP.net WebService can be hosted outside of IIS like ASP.net web service can be hosted in a Windows Service.
WCF service is flexible because it can be hosted in IIS, Windows Activation Services(WAS), Managed Windows Services and It also supports Self-Hosting.
3
Transport Protocols/Binding
ASP.net Web service supports HTTP & TCP protocols along with custom binding.
WCF service supports HTTP, WS-HTTP, TCP, Custom, Named Pipes, MSMQ & P2P(Point to Point) etc.
4
Data Transformation
It uses XML serializer for Data Transformation.
WCF service uses DataContractSerializer for Data Transformation.
5
Serialization NameSpace
System.XML.Serialization
System.RunTime.Serialization
6
Supported Operations
The supported operations are only One-Way and Request-Response type.
The supported operations includes One-Way, Request-Response and Duplex.
7
Encoding
It uses following encoding mechanisms -
XML1.0, MTOM (Message Transmission Optimization Mechanism), DIME (Direct Internet Message Encapsulation)
It uses following encoding mechanisms -
XML1.0, MTOM, Binary
8
WebMethods and DataContract
Uses WebMethods to translate .Net FW types in to XML.
  • [WebService] attribute has to be added to into the class.
  • [WebMethod] attribute represents the method exposed to the client.
Uses DataContractAttributes and DataMemberAttribute to translate .Net FW types in to XML.
  • [ServiceContract] attribute has to be added to into the class.
  • [OperationContract] attribute represents the method exposed to the client.
9
Messaging
Asp.Net web service supports only SOAP(Simple Object Access Protocol) as messaging service.
WCF service can send/receive message through any transport protocol message format. However, by default it uses SOAP for communication.
10
Security
This is not much secured as compared to WCF. It is less secured to protect data between Server and Client. Certificates can protect the data but it is very complicated to use Certificates. For security, normally we use UserName/Password.
As compared to ASP.net web service, WCF services are more secured. WCF does not need IIS to run, it can run as a System Service on the Server, using a command ambient. We can say that WCF is a service and not a Web Service.
11
Performance
Performance wise web services are slower than WCF service.
WCF services are than WebService. The performance measures in terms of xml serialization.
12
Exception Handling
This returns all unhandled exceptions to the client as SOAP faults.
WCF does not returns unhandled Exceptions to the client as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to the Client for the purpose of debugging.
13
Limitations
  • Hash Table cannot be serialized.
  • Only public properties/fields can be serialized
  • The DataContractSerializer translate the Hash table into the XML.
  •  Public/Private properties/fields can be serialized.