Thursday, 28 April 2016

Submitting form and post data dynamically in c#

No comments

here for sudopay api as example to post data instead of using form

from form - 

<form action="http://sandbox.sudopay.com/api/v1/merchants/11/websites/78/vaults/type/cc.json" method="post">
        <input name="user_handle" type="hidden" value="703212898983" />
        <input name="email" type="hidden" value="test@example.com" />
        <input name="credit_card_number" type="hidden" value="4111111111111111" />
        <input name="credit_card_expire" type="hidden" value="10/2016" />
        <input name="credit_card_type" type="hidden" value="visa" />
        <input name="credit_card_name_on_card" type="hidden" value="Fred" />
        <input name="email" type="hidden" value="test@example.com" />
        <input name="address" type="hidden" value="First Street" />
        <input name="city" type="hidden" value="Chennai" />
        <input name="state" type="hidden" value="Tamil Nadu" />
        <input name="country" type="hidden" value="IN" />
        <input name="buyer_ip" type="hidden" value="201.200.01.01" />
        <input name="zip_code" type="hidden" value="38005" />
        <input name="phone" type="hidden" value="9662542112" />
        <input name="success_url" type="hidden" value="https://sudopay.com//?pa=success#sudopay-demo" />
        <input name="cancel_url'" type="hidden" value="https://sudopay.com//?pa=failure#sudopay-demo" />
        <input name="submit" class="btn btn-large" type="submit" value="Pay $1" />
    </form>


instead from c# -

        private static System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
 static void Main(string[] args)
        {            
            Inputs.Add("user_handle", "009199199999199");
            Inputs.Add("email", "test@example.com");
            Inputs.Add("credit_card_number", "4111111111111111");
            Inputs.Add("credit_card_expire", "10/2016");
            Inputs.Add("credit_card_type", "visa");
            Inputs.Add("credit_card_name_on_card", "Fred");
            Inputs.Add("email", "test@example.com");
            Inputs.Add("address", "First Street");
            Inputs.Add("city", "Chennai");
            Inputs.Add("state", "Tamil Nadu");
            Inputs.Add("country", "IN");
            Inputs.Add("zip_code", "38005");
            Inputs.Add("phone", "9662542112");
            Inputs.Add("buyer_ip", "201.200.01.01");

            WebClient client = new WebClient();
            client.Headers.Add("Authorization", "Basic MTEzMzc6ZDNkMDhkOGI0YzNlY2NmOGI0ODg3ZDhmN2QxYTc3ZGYxNzY1ZGVkNQ==");
            byte[] response = client.UploadValues("http://sandbox.sudopay.com/api/v1/merchants/11/websites/78/vaults/type/cc.json", Inputs);
            string result = System.Text.Encoding.UTF8.GetString(response);
        }


here authorization key like "MTEzMzc6ZDNkMDhkOGI0YzNlY2NmOGI0ODg3ZDhmN2QxYTc3ZGYxNzY1ZGVkNQ==" can be get from fiddler 
goto tools and textwizard , enter username and password which will return base 64 encoded url use that as authentication


read more

Monday, 25 April 2016

Binding country state city in mvc

No comments
CountryRepository.cs
--------------------------
public class CountryRepository : Repository<Country>
    {
        private DataBaseContext _context = null;
        public CountryRepository(DataBaseContext context, UnitOfWork _uom)
            : base(context, _uom)
        {
            _context = context;
        }

        public List<Country> GetAllCountries()
        {
            return base.GetAll().ToList().OrderBy(x => x.SortCode).ThenBy(y => y.CountryName).ToList();
            //.OrderBy(x => new { x.SortCode }).ThenBy(y => y.CountryName)
        }

        public string GetCountryCode(int countryId)
        {
            return base.GetAll(x => x.CountryId == countryId).Select(x => x.CountryCode).ToString();
        }

        public string GetCountryName(int countryId)
        {
            return base.Get(x => x.CountryId == countryId).CountryName;
        }
    }


StateRepository.cs
-----------------------
 public class StateRepository : Repository<State>
    {
        private DataBaseContext _context = null;
        public StateRepository(DataBaseContext context, UnitOfWork _uom)
            : base(context, _uom)
        {
            _context = context;
        }

        public List<State> GetAllStates(int countryId)
        {
            return base.GetAll(x => x.CountryId == countryId).ToList();
        }

        public List<State> GetStateCode()
        {
            return base.GetAll().ToList();
        }      
    }

HomeController.cs
-------------------------


  public void BindDropDownListShipment(Model model)
        {
            UnitOfWork uow = new UnitOfWork();      
            //Bind Country For From Address
            model.CountryList = GenericSelectListItems.Instance.GetAllCountries();
            //Bind State For From Address                            
            model.StateList = GenericSelectListItems.Instance.GetAllStates(model.CountryId);          
        }

View
------------
    <div class="form-group">
  <label>Country<span class="text-red">*</span></label>
  @Html.DropDownListFor(m => m.CountryId, Model.CountryList, "Select Country", new { @class = "form-control  required", @data = "Country" })
  </div>
  </div>                                    
  <div class="col-md-4">
  <div class="form-group">
  <label>State<span class="text-red">*</span></label>
  @Html.DropDownListFor(m => m.StateId, Model.StateList, "Select State", new { @class = "form-control" })
 </div>
 </div>


 //Add new option
            function AddNewOptionToStateDropdown(id) {
                var newOption1 = $('<option selected="selected">');
                newOption1.attr('value', 0).text("Select State");
                $('#' + id).append(newOption1);
            }


//Get states from country
                $('#CountryId').change(function () {
                    $('#StateId').empty();
                    AddNewOptionToStateDropdown('StateId');

                    if (isNaN(parseInt($(this).val()))) {
                        return;
                    }
                        var CountryList = $('#CountryId :selected').text();
                        $('#StateId').css('pointer-events', 'auto');
                        $.ajax({
                            method: "GET",
                            url: "@Url.Action("GetStateByCountryAndZip", "Home")",
                            data: { 'CountryName': CountryList },
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (result) {
                                if (result != undefined && result != null) {
                                    $('#City').empty();
                                    $('#City').val(result["City"]);
                                    var newOption1 = $('<option selected="selected">');
                                    newOption1.attr('value', result["State"]).text(result["State"]);
                                    $('#StateId').append(newOption1);
                                }
                            },
                            failure: function () {
                            }
                        });
                    }
                });



read more

Sending Json Data to Controller and return json data

No comments
View
---------

$('#Client').click(function () {
               $.ajax({
                            method: "GET",
                            url: "@Url.Action("GetClients", "Home")",
                            data: { 'Name': 'Vikas', 'Code': '4049' },
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (result) {
                                if (result != undefined && result != null) {
                                  alert('ok');
                                }
                                else {
                                  alert('not found');
                                }
                            },
                            failure: function () {
                               alert('error');
                            }
                        });
               });



controller.cs
------------------

 public string GetClients(string Name, string Code)
        {          
            UnitOfWork uow = new UnitOfWork();
            var postalData = uow.Repository<GetClientRepository>();
            var result = postalData.GetClient(Name, Code).FirstOrDefault();
            return Newtonsoft.Json.JsonConvert.SerializeObject(result);
        }
read more

Email Factory to use email sending in background

No comments
GenericListAppconfig.cs
---------------------------------
public class GenericListAppconfig
    {
        private static GenericListAppconfig _GenericListAppconfig = new GenericListAppconfig();
        UnitOfWork uom = new UnitOfWork();
        private GenericListAppconfig()
        {

        }

        public static GenericListAppconfig intance
        {
            get{
                return _GenericListAppconfig;
            }
        }

        public List<AppConfig> GetAppConfigData(string groupName)
        {
            var appConfigData = uom.Repository<AppconfigRepository>();
            var appConfigList = appConfigData.GetAllAppConfig(groupName);
            return appConfigList.ToList();
        }      
    }
 


EmailNotification.cs
------------------------------
 public void SendMail(string toEmail, string subject,string fromEmail, string body,string attachmentFile)
        {
            MailMessage mail = new MailMessage();
            var appDataList = GenericListAppconfig.intance.GetAppConfigData("smtp");
            SmtpClient smtpServer = new SmtpClient(appDataList.FirstOrDefault(x => x.name == "smtp.host").Value);
            smtpServer.UseDefaultCredentials = true;          
            smtpServer.Credentials = new System.Net.NetworkCredential(appDataList.FirstOrDefault(x => x.name == "smtp.username").Value, appDataList.FirstOrDefault(x =>                                                                             x.name == "smtp.password").Value);

            if (!string.IsNullOrEmpty(attachmentFile))
            {
                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment(attachmentFile);
                mail.Attachments.Add(attachment);
            }

            smtpServer.Port = Convert.ToInt32(appDataList.FirstOrDefault(x => x.name == "smtp.port").Value);        
            smtpServer.EnableSsl = true;
         
            mail.From = new MailAddress(fromEmail);
            mail.IsBodyHtml = true;
            mail.To.Add(toEmail);
            mail.Subject = subject;
            mail.Body = body;
            mail.Priority = MailPriority.High;
            Task.Factory.StartNew(() => smtpServer.Send(mail), TaskCreationOptions.LongRunning);
         
        }


using EmailNotification in controller
----------------------------------------------

 string filePath = Server.MapPath("~/" + Express.Web.Models.GenericListAppconfig.intance.GetAppConfigData("Client").FirstOrDefault(x => x.name == "Client.path").Value + "/" + id + "/" + id + ".pdf");

            EmailNotification EmailNotification = new Utils.EmailNotification();
            var appDataList = GenericListAppconfig.intance.GetAppConfigData("smtp");
            EmailNotification.SendMail(email, "Shipment Details", appDataList.FirstOrDefault(x => x.name == "smtp.noreply").Value, htmlBody.ToString(), filePath);

read more

Creating Factory To Use Property Of Class Everywhere - SessionFactory

No comments
SessionFactory.CS -

 public class SessionFactory
    {
        private static SessionFactory _SessionFactory = new SessionFactory();
        private SessionFactory()
        {

        }
        public static SessionFactory Instance
        {
            get
            {
                return _SessionFactory;
            }
        }

      public Customer CurrentCustomer
        {
            get
            {
                if (HttpContext.Current.Session["user"] == null)
                {                  
                    return null;
                }
                return (Customer)HttpContext.Current.Session["user"];
            }
            set
            {
                HttpContext.Current.Session["user"] = value;
            }
        }
}


using SessionFactory.CS in controller
------------------------------------------------
 UnitOfWork uom = new UnitOfWork();
 uom.BeginTransaction();
 var updateCustomer = uom.Repository<SignUpRepository>();
 var resultCustomer = updateCustomer.Get(x => x.CustomerId ==  SessionFactory.Instance.CurrentCustomer.CustomerId);
 resultCustomer.CreditLimit = SessionFactory.Instance.CurrentCustomer.CreditLimit;
 updateCustomer.UpdateCustomer(resultCustomer);
 uom.Commit();

read more

MVC Repository Pattern With EntityFramwork- Getting Started

No comments

first we will create 3 projects in one solution for starting up our project

1. Test.Web - which contains our mvc project (MVC Project)
2. Repository.Pattern - which contains repository pattern
3. Test.Entities - which contains classes of database table


prerequisite - add entity framework from

1.Test.Web
------------------

create MVC project and create controller and view

HomeController.cs  -

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
  }


2. Repository.Pattern - 
------------------------------

add DataBaseContext.cs , unitofwork.cs for DbContext

DataBaseContext.cs -

  public class DataBaseContext : DbContext
    {
        private DbSet<Customer> Registration { get; set; }  

        public DataBaseContext()
            : base("Name=ConnectionString")
        {
            Configuration.LazyLoadingEnabled = false;
            Configuration.ProxyCreationEnabled = false;
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        }
    }

Unitofwork.cs - 

public class UnitOfWork : IDisposable
    {
        #region Declaration
        private DataBaseContext entities = null;
        private DbContextTransaction _transaction;
        #endregion

        #region Ctor
        public UnitOfWork()
        {
            //entities = new DBContext(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            entities = new DataBaseContext();

        }
        #endregion

        #region Create Repository Instance
        public T Repository<T>() where T : class
        {
            Object[] args = { entities, this };

            var repository = Activator.CreateInstance(typeof(T), args);
            return (T)repository;
        }

        private Dictionary<Type, object> repositories = new Dictionary<Type, object>();
        public IRepository<T> RepositoryInstance<T>() where T : class
        {
            if (repositories.Keys.Contains(typeof(T)) == true)
            {
                return repositories[typeof(T)] as IRepository<T>;
            }
            IRepository<T> repo = new Repository<T>(entities, this);
            repositories.Add(typeof(T), repo);
            return repo;
        }

        #endregion

        #region DB Transactions
        public void BeginTransaction()
        {
            _transaction = entities.Database.BeginTransaction();
        }
        public bool Commit()
        {
            _transaction.Commit();
            return true;
        }
        public void Rollback()
        {
            _transaction.Rollback();
        }
        public void SaveChanges()
        {
            entities.SaveChanges();
        }
        #endregion

        #region Dispose
        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    entities.Dispose();
                }
            }
            this.disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion
    }

IRepository.cs -

 public interface IRepository<T> where T : class
    {
        IEnumerable<T> GetAll(Func<T, bool> predicate = null);
        T Get(Func<T, bool> predicate);
        void Add(T entity);
        void AddRange(List<T> entity);
        void Attach(T entity);
        void Update(T entity);
        void Delete(T entity);
        void DeleteRange(List<T> entity);
        IEnumerable<T> ExecWithStoreProcedure(string query, params object[] parameters);
        //T FindSingleBy<T>(Expression<Func<T, bool>> predicate);
        //IQueryable<T> FindAllBy<T>(Expression<Func<T, bool>> predicate);
        //IQueryable<T> FindBy<T, TKey>(Expression<Func<T, bool>> predicate, Expression<Func<T, TKey>> orderBy);

    }


Repository.cs - 


  public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    {
        private DataBaseContext _context = null;
        private readonly DbSet<TEntity> _dbSet;
        UnitOfWork uom = null;
        public Repository(DataBaseContext context, UnitOfWork _uom)
        {
            _context = context;
            uom = _uom;
            var dbContext = context as DbContext;

            if (dbContext != null)
            {
                _dbSet = dbContext.Set<TEntity>();
            }
        }
        public IEnumerable<TEntity> GetAll(Func<TEntity, bool> predicate = null)
        {
            if (predicate != null)
            {
                return _dbSet.Where(predicate);
            }

            return _dbSet.AsEnumerable();
        }
        public TEntity FindSingleBy<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
        {
            if (predicate != null)
            {
                using (_context = new DataBaseContext())
                {
                    return _context.Set<TEntity>().Where(predicate).SingleOrDefault();
                }
            }
            else
            {
                throw new ArgumentNullException("Predicate value must be passed to FindSingleBy<T>.");
            }
        }

        public virtual IQueryable<TEntity> FindAllBy<TEntity>(Expression<Func<TEntity, bool>> predicate, DataBaseContext _context) where TEntity : class
        {
            if (predicate != null)
            {
                return _context.Set<TEntity>().Where(predicate);
            }
            else
            {
                throw new ArgumentNullException("Predicate value must be passed to FindAllBy<T>.");
            }
        }

        public IQueryable<TEntity> FindBy<TEntity, TKey>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, TKey>> orderBy) where TEntity : class
        {
            if (predicate != null)
            {
                if (orderBy != null)
                {
                    using (_context = new DataBaseContext())
                    {
                        return FindAllBy<TEntity>(predicate, _context).OrderBy(orderBy).AsQueryable<TEntity>(); ;
                    }
                }
                else
                {
                    throw new ArgumentNullException("OrderBy value must be passed to FindBy<T,TKey>.");
                }
            }
            else
            {
                throw new ArgumentNullException("Predicate value must be passed to FindBy<T,TKey>.");
            }
        }

        public TEntity Get(Func<TEntity, bool> predicate)
        {
            return _dbSet.FirstOrDefault(predicate);
        }

        public void Add(TEntity entity)
        {
            _dbSet.Add(entity);
            uom.SaveChanges();
        }

        public void AddRange(List<TEntity> entity)
        {
            _dbSet.AddRange(entity);
            uom.SaveChanges();
        }

        public void Update(TEntity entityToUpdate)
        {
            var entry = _context.Entry(entityToUpdate);
            var key = this.GetPrimaryKey(entry);

            if (entry.State == EntityState.Detached)
            {
                var currentEntry = _dbSet.Find(key);
                if (currentEntry != null)
                {
                    var attachedEntry = _context.Entry(currentEntry);
                    attachedEntry.CurrentValues.SetValues(entityToUpdate);
                }
                else
                {
                    _dbSet.Attach(entityToUpdate);
                    entry.State = EntityState.Modified;
                }
            }
        }

        private int GetPrimaryKey(DbEntityEntry entry)
        {
            var myObject = entry.Entity;
            var property =
                myObject.GetType()
                    .GetProperties()
                    .FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(KeyAttribute)));
            return (int)property.GetValue(myObject, null);
        }

        public void Attach(TEntity entity)
        {
            _dbSet.Attach(entity);
            _context.Entry(entity).State = EntityState.Modified;
            uom.SaveChanges();
        }

        public void Delete(TEntity entity)
        {
            _context.Entry(entity).State = EntityState.Deleted;
            _dbSet.Remove(entity);
            uom.SaveChanges();
        }
        public void DeleteRange(List<TEntity> entity)
        {
            _dbSet.RemoveRange(entity);
            uom.SaveChanges();
        }
        public IEnumerable<TEntity> ExecWithStoreProcedure(string query, params object[] parameters)
        {
            return _context.Database.SqlQuery<TEntity>(query, parameters);
        }

    }


Create Customer repository noe

ContactsRepository.cs


 public class ContactsRepository: Repository<Contacts>
    {
        private DataBaseContext _context = null;
        public ContactsRepository(DataBaseContext context, UnitOfWork _uom)
            : base(context, _uom)
        {
            _context = context;
        }
        public void AddContacts(Contacts Contacts)
        {
            var dbset = _context.Set<Contacts>();
            dbset.Add(Contacts);
            _context.SaveChanges();
        }
     

        public Contacts GetContactsById(int contactId)
        {
            var dbset = _context.Set<Contacts>();
            var contacts = dbset.FirstOrDefault(x => x.ContactsId == contactId);
            if (contacts != null)
            {
                return contacts;
            }
            return null;

        }


    }


3.Test.Entities
--------------------


   public class Contacts
    {
        [Key]
        public int ContactsId { get; set; }
        public int CustomerId { get; set; }
        [Required]
        [StringLength(35)]
        public string Address1 { get; set; }
        [StringLength(35)]
        public string Address2 { get; set; }
        [Required]

        public int CountryId { get; set; }
        //[Required]

        public string StateId { get; set; }
        [Required]
        [StringLength(50)]
        public string City { get; set; }
        [Required]
        [StringLength(10)]
        public string ZIP { get; set; }
        [Required]
        [StringLength(15)]
}

using repository in controller--

HomeController.cs  -

 public class HomeController : Controller
    {
        public ActionResult Index()
        {
                 var insertContacts = uom.Repository<ContactsRepository>();
                Contacts contacts = new Contacts();
                contacts.CustomerId = SessionFactory.Instance.CurrentCustomer.CustomerId;
                contacts.Address1 = shipmentModel.ShipFrom.Address1;
                contacts.Address2 = shipmentModel.ShipFrom.Address2;
                contacts.CountryId = shipmentModel.ShipFrom.CountryId;
                contacts.StateId = shipmentModel.ShipFrom.StateId;
                contacts.City = shipmentModel.ShipFrom.City;
                contacts.ZIP = shipmentModel.ShipFrom.ZIP;
                contacts.Phone = shipmentModel.ShipFrom.Phone;              
                insertContacts.AddContacts(contacts);              
                return View();
        }
  }
read more

Sunday, 2 August 2015

Web Api -Get and Post Data From Client(Html) And Server(ASPX) Side

No comments
- First create new project as web api project
- First Edit WebConfig File To  Add AppSettings

WebConfig:

<configuration> 
  <appSettings>
    <add key="DataSource" value="TEST" />
    <add key="InitialCatalog" value="TestProject" />
    <add key="UserID" value="sa" />
    <add key="Password" value="sql2008" />
    <add key="ServerName" value="localhost" />
  </appSettings>
</configuration>

 - Create New Folder "MyHelperLib" and Add New Class File "APICommonUtil.cs"

APICommonUtil.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

namespace D2D.WebAPI.MyHelperLib
{
    public class APICommonUtil
    {
        internal static string GetDBConnString()
        {
            SqlConnectionStringBuilder oSQLConnStr = new SqlConnectionStringBuilder();
            oSQLConnStr.DataSource = WebConfigurationManager.AppSettings["DataSource"].ToString();
            oSQLConnStr.InitialCatalog = WebConfigurationManager.AppSettings["InitialCatalog"].ToString();
            oSQLConnStr.UserID = WebConfigurationManager.AppSettings["UserID"].ToString();
            oSQLConnStr.Password = WebConfigurationManager.AppSettings["Password"].ToString();
            return oSQLConnStr.ToString();
        }
    }
}

- Add new Controller as TestController

TestController.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Http;
using System.Web.Routing;
using System.Web.Script.Serialization;

[RoutePrefix("api/test")]
public class UserController : ApiController
{
    #region "Connection String"
    string MyConnectionString = D2D.WebAPI.MyHelperLib.APICommonUtil.GetDBConnString();
    #endregion

    #region ''

    // GET api/<controller>
    public IEnumerable<string> GetValues()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5

    public string GetValue(int id)
    {
        return "value";
    }
    // POST api/<controller>
    public void PostValue([FromBody]string data)
    {

    }
    // PUT api/<controller>/5

    public void PutValue(int id, [FromBody]string data)
    {

    }
    // DELETE api/<controller>/5
    public void DeleteValue(int id)
    { }

    #endregion

    #region "Get"

 
    /**Get Method To Get Data**/

    [Route("UserInfo//{UserId}")]
    public DataSet GetRoleMenu(string UserId)
    {
        using (SqlConnection connection = new SqlConnection(MyConnectionString))
        {
            connection.Open();
            SqlCommand cmd = new SqlCommand("select * from UserInfo Where        UserId='"+UserId+"'", connection);       
            SqlDataAdapter adpt = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adpt.Fill(ds);
            ds.Tables[0].TableName = "Users";

            if (ds.Tables[0].Rows.Count == 0)
            {
                throw new Exception("Unable to find any User.");
            }
            else
            {
                return ds;
            }
        }
    }

    #endregion

    #region "POST api/<controller>"

    /*Post Method To Insert-Update User*/
  //With QueryString
    [HttpPost]
    [Route("UserInfo}")]
    public int SetUserInfo()
    {      
        NameValueCollection User= HttpUtility.ParseQueryString(Request.RequestUri.Query);
        SqlConnection connection = new SqlConnection(MyConnectionString);
        SqlCommand cmd = new SqlCommand("spAddUpdateUser", connection);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter adpt = new SqlDataAdapter(cmd);
        //string server = WebConfigurationManager.AppSettings["ServerName"].ToString();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@UserId", Item[0] == "" ? DBNull.Value.ToString() : User[0]);
        cmd.Parameters.AddWithValue("@UserName", Item[1] == "" ? DBNull.Value.ToString() : User[1]);   
        cmd.Connection = connection;
        int UserId= 0;
        try
        {
            connection.Open();
            UserId= (int)cmd.ExecuteScalar();
        }
        catch (Exception)
        { }
        finally
        {
            connection.Close();
        }
        return itemId;
    }
    #endregion
}

-  Create Wrapper.js File To Post And Get Data From Client Side i.e From HTML Page

Wrapper.jsvar APIWrapper = function (url) {

    var Priviliged = {
        myWebReqUrl: null,

        WebApiUriConstant: function () {
            try {
                var apiUri = "http://localhost/WebAPI/api";           
            } catch (e) {
                //alert(e.stack);
            }
            return apiUri;
        },

        CallWebAPI: function (webApiUrl, isAsync, myCallBackOnSuccess, myCallBackOnFailure) {

            var sData = "";
            try {
                $.ajax({
                    type: "GET",
                    url: webApiUrl,
                    data: sData,
                    async: isAsync,
                    contentType: "application/json;",
                    dataType: "json",
                    success: function (data) {
                        if (myCallBackOnSuccess != null); myCallBackOnSuccess(data);

                    },
                    error: function (xhr, status, error) {

                        var errorMessage = '';
                        try {
                            var xhr = JSON.parse(xhr.responseText);
                            errorMessage = xhr.ExceptionMessage;
                        } catch (e) {
                            errorMessage = "";
                        }

                        if (myCallBackOnFailure != null); myCallBackOnFailure(xhr.responseText);
                    }
                });
            }
            catch (e) {
                //alert(e.stack);
                //TODO - Display error message in popup screen.
            }
        },

        PostWebAPI: function (webApiUrl, isAsync, myCallBackOnSuccess, myCallBackOnFailure) {

            var sData = "";
            try {
                $.ajax({
                    type: "POST",
                    url: webApiUrl,
                    data: sData,
                    async: isAsync,
                    contentType: "application/json;",
                    dataType: "json",
                    sucess: function (data) {
                        if (myCallBackOnSuccess != null);
                        myCallBackOnSuccess(data);
                    },
                    error: function (xhr, satus, error) {
                        var errorMessage = "";
                        try {
                            var xhr = JSON.parse(xhr.responseText);
                            errorMessage = xhr.ExceptionMessage;
                        }
                        catch (e) {
                            errorMessage = "";
                        }
                        if (myCallBackOnFailure != null);
                        myCallBackOnFailure(xhr.responseText);
                    }
                });
            }
            catch (e) {
                //alert(e.stack);
                //TODO - Display error message in popup screen.
            }
        }
    };//End Priviliged


    var External = {

        /***** Start User Public function for the js  *****/

        InsertUser: function (UserDetail, myCallBackOnSuccess, myCallBackOnError) {
          Priviliged.myWebReqUrl = Priviliged.WebApiUriConstant() + "/UserInfo/?UserId=" + UserDetail.UserId+
                                                                                    "&UserName=" + UserDetail.UserName;
            Priviliged.PostD2DWebAPI(Priviliged.myWebReqUrl, false, callBackOnSuccess, callBackOnError)
        },      

        GetUser: function (UserId, callBackOnSuccess, callBackOnError) {
            Priviliged.myWebReqUrl = Priviliged.WebApiUriConstant() + "/UserInfo/" + UserId;
            Priviliged.CallD2DWebAPI(Priviliged.myWebReqUrl, true, callBackOnSuccess, callBackOnError)
        },
   }
}


-  Now Call This Wrapper.Js Function To HTML Page Where Data Is Sent

Test.html:


//
Insert User
 var BindUser= ({ UserId: $('#txtUser').val(), UserName: $('#txtUserName').val()});
APIWrapper.InsertUser(BindUser, function (objUser) {                 }, function () {
                    });

//GET User
APIWrapper.GetUser(hdnUserId,function (objUser) {
            try {
                if (objUser!= null && objUser!= undefined && objUser.Users.length > 0) {
//Bind DropDownList With Get Data
                    $.each(objUser.Users, function (index, item) {
                        $("#cmbUser").get(0).options[$("#cmbUser").get(0).options.length] = new Option(item.UserName, item.UserId);                  
                    });
                }
            }
            catch (e) {
            }
        }, function () {
        });
/********************** TO Get And Post Data From Server Side ********************/
- First create ApiCall.cs

ApiCall.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Helper
{
    public class ApiCall
    {
        private string JSON = "";

        //Get
        public string GetFromWebService(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            JSON = "";
            try
            {
                request.Timeout = 60000;
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    //System.Threading.Thread.Sleep(500);
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    string value = reader.ReadToEnd();
                    JSON = value;
                    return value;
                }
            }
            catch (WebException ex)
            {
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                    // log errorText
                }
                throw;
            }
        }

        // POST a JSON string
        public string PostToWebService(string url, string jsonContent)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Timeout = 6000;

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(jsonContent);

            request.ContentLength = byteArray.Length;
            request.ContentType = @"application/json";

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }

            long length = 0;
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    length = response.ContentLength;
                    var value = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    JSON = value;
                    return JSON;
                    //JSONObject = response;
                }
            }
            catch (WebException ex)
            {
                // Log exception and throw as for GET example above
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                    // log errorText
                }
                throw;
            }
        }
    }
}
- Now Call ApiCall.cs Method From ASPX Code Behinde

Test.aspx
//To Post Data
protected void btnSave_Click(object sender, EventArgs e)
        {
            string URL_ADDRESS = String.Format("http://localhost/WebAPI/api/UserInfo/{0}/{1}", txtUserId.Text, txtUserName.Text);
            ApiCall objAPICall = new ApiCall();
            objAPICall.PostToWebService(URL_ADDRESS, "");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "Clear", "clear()", true);  
        }

read more