none
405, Method Not allowed RRS feed

  • Question

  • This is my Wcf Service..

    Here it is Serice.svc.cs..

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    using System.Data.SqlClient;
    using System.Data;
    using System.ServiceModel.Activation;
    
    namespace DBWCFService
    {
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        public class Service1 : IService1
        {
            
            List<EmployeeDetails> Employees = new List<EmployeeDetails>();
    
    
            // gets employee data
            public List<EmployeeDetails> GetEmployees()
            {
    
                {
                    SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Viswa_Attendance_System\\DBWCFService\\DBWCFService\\App_Data\\RegisterData.mdf;Integrated Security=True;User Instance=True");
                    con.Open();
                    SqlCommand cmd = new SqlCommand("select * from RegisterTable", con);
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
    
                        EmployeeDetails empInfo = new EmployeeDetails();
                        empInfo.Emp_Id = Convert.ToInt32(reader["Emp_ID"]);
                        empInfo.Emp_Name = Convert.ToString(reader["Emp_Name"]);
                        empInfo.Password = Convert.ToString(reader["Password"]);
                        empInfo.Cnf_Password = Convert.ToString(reader["Cnf_Password"]);
                        empInfo.Email = Convert.ToString(reader["Email"]);
                        Employees.Add(empInfo);
                    }
                    return Employees.ToList();
                    con.Close();
                }
                
    
            }
    
    
            //Gets Employee data by ID
            public List<EmployeeDetails> getEmployeesbyID(string empid)
            {
                List<EmployeeDetails> employees = new List<EmployeeDetails>();
                SqlConnection con1 = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Viswa_Attendance_System\\DBWCFService\\DBWCFService\\App_Data\\RegisterData.mdf;Integrated Security=True;User Instance=True");
                con1.Open();
                {
                    
                    
                    SqlCommand cmd = new SqlCommand("select * from RegisterTable where Emp_ID ="+ empid, con1);
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    { 
    
                        EmployeeDetails empInfo = new EmployeeDetails();
                        empInfo.Emp_Id = Convert.ToInt32(reader["Emp_ID"]);
                        empInfo.Emp_Name = Convert.ToString(reader["Emp_Name"]);
                        empInfo.Password = Convert.ToString(reader["Password"]);
                        empInfo.Cnf_Password = Convert.ToString(reader["Cnf_Password"]);
                        empInfo.Email = Convert.ToString(reader["Email"]);
                        Employees.Add(empInfo);
                    }
                    return Employees.ToList();
    
                }
                con1.Close();
            }
    
            // Inserting employee data
            public string InsertEmployeeDetails(EmployeeDetails empInfo)
            {
                string Message;
    
                string connectionString ="Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Viswa_Attendance_System\\DBWCFService\\DBWCFService\\App_Data\\RegisterData.mdf;Integrated Security=True;User Instance=True";
                using (SqlConnection connection = new SqlConnection())
                {
                    connection.ConnectionString = connectionString;
                    connection.Open();
                    SqlCommand cmd = connection.CreateCommand();
                    string sql = "insert into RegisterTable(Emp_Id,Emp_Name,Password,Cnf_Password,Email) values(@Emp_ID,@Emp_Name,@Password,@Cnf_Password,@Email)";
                    //// cmd.Parameters.AddWithValue("@Emp_ID",empInfo.Emp_Id);            
                    // cmd.Parameters.AddWithValue("@Emp_Name", empInfo.Emp_Name);
                    // cmd.Parameters.AddWithValue("@Password", empInfo.Password);
                    // cmd.Parameters.AddWithValue("@Cnf_Password", empInfo.Cnf_Password);
                    // cmd.Parameters.AddWithValue("@Email", empInfo.Email);
                    cmd.CommandText = sql;
                    cmd.Parameters.Add(new SqlParameter("@Emp_ID", empInfo.Emp_Id));
                    cmd.Parameters.Add(new SqlParameter("@Emp_Name", empInfo.Emp_Name));
                    cmd.Parameters.Add(new SqlParameter("@Password", empInfo.Password));
                    cmd.Parameters.Add(new SqlParameter("@Cnf_Password", empInfo.Cnf_Password));
                    cmd.Parameters.Add(new SqlParameter("@Email", empInfo.Email));
                    int result = cmd.ExecuteNonQuery();
                    if (result == 1)
                    {
                        Message = empInfo.Emp_Id + "Details inserted Successfully";
                    }
                    else
                    {
                        Message = empInfo.Emp_Id + "Error occured, Details not inserted";
                    }
                    return Message;
    
    
                }
            }
    
    
            //Deleting employee By ID
            public bool DeleteEmployeeById(string empid)
            {
                string connectionString = @"Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Viswa_Attendance_System\\DBWCFService\\DBWCFService\\App_Data\\RegisterData.mdf;Integrated Security=True;User Instance=True";
                using (SqlConnection connection = new SqlConnection())
                {
                    connection.ConnectionString = connectionString;
                    connection.Open();
                    SqlCommand command = connection.CreateCommand();
                    string sql = "Delete RegisterTable where Emp_ID=" + empid;
                    command.CommandText = sql;
                    command.ExecuteNonQuery();
                    return true;
                }
            }
    
            //Updatiing Employee
            public bool UpdateEmployee(EmployeeDetails Emp)
            {
                string connectionString = @"Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Viswa_Attendance_System\\DBWCFService\\DBWCFService\\App_Data\\RegisterData.mdf;Integrated Security=True;User Instance=True";
                using (SqlConnection connection = new SqlConnection())
                {
                    connection.ConnectionString = connectionString;
                    connection.Open();
                    SqlCommand command = connection.CreateCommand();
                    string sql = "update RegisterTable set Emp_ID='" + Convert.ToString(Emp.Emp_Id) + "',Emp_Name='" + Convert.ToString(Emp.Emp_Name) + "' Password='" + Convert.ToString(Emp.Password) + "',Cnf_Password='" + Convert.ToString(Emp.Cnf_Password) + "',Email='" + Convert.ToString(Emp.Email) + "' where Emp_Id=" + Convert.ToString(Emp.Emp_Id);
                    command.CommandText = sql;
                    command.ExecuteNonQuery();
                    return true;
                }
            }
    
        }
    }
    

    Then, Here.. IService.cs..

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.Text;
    
    namespace DBWCFService
    {
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
        [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
            List<EmployeeDetails> GetEmployees();
    
            [OperationContract]
            [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
            List<EmployeeDetails> getEmployeesbyID(string empid);
    
    
            [OperationContract]
            [WebInvoke(Method = "POST",
                 UriTemplate = "/InsertEmployeeDetails",
                 RequestFormat = WebMessageFormat.Json,
                 ResponseFormat = WebMessageFormat.Json)]
            string InsertEmployeeDetails(EmployeeDetails empInfo);
    
            //[OperationContract]
            //[WebInvoke(Method = "POST",
            //BodyStyle = WebMessageBodyStyle.Bare,
            //RequestFormat = WebMessageFormat.Json,
            //ResponseFormat = WebMessageFormat.Json)]
            //void InsertEmployeeDetails(EmployeeDetails empInfo);
    
    
            [OperationContract]
            [WebInvoke(Method = "POST",
                UriTemplate = "/deleteEmployee/{empid}",
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json)]
            bool DeleteEmployeeById(string empid);
    
    
            [OperationContract]
            [WebInvoke(Method = "POST",
                UriTemplate = "/UpdateEmployee",
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json)]
            bool UpdateEmployee(EmployeeDetails Emp);
    
    
    
        }
    
        [DataContract]
        public class EmployeeDetails
        {
           public int emp_Id;
           public string emp_Name;
           public string password;
           public string confirmPassword;
           public string email;
    
            [DataMember]
            public int Emp_Id
            {
                get { return emp_Id; }
                set { emp_Id = value; }
            }
            [DataMember]
            public string Emp_Name
            {
                get { return emp_Name; }
                set { emp_Name = value; }
            }
            [DataMember]
            public string Password
            {
                get { return password; }
                set { password = value; }
            }
            [DataMember]
            public string Cnf_Password
            {
                get { return confirmPassword; }
                set { confirmPassword = value; }
            }
            [DataMember]
            public string Email
            {
                get { return email; }
                set { email = value; }
            }
        }
    }
    

    Client side using JSON, Ajax formation...

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Calling WCF service</title>
        <link href="CSS/Employee.css" rel="stylesheet" type="text/css" />
        <link href="CSS/ui.jqgrid.css" rel="stylesheet" type="text/css" />
        <script src="JS/jquery-1.11.1.js" type="text/javascript"></script>
        <script src="JS/jquery-1.11.1.min.js" type="text/javascript"></script>
        <script src="JS/jquery-1.7.2.min.js" type="text/javascript"></script>
        <script src="JS/grid.locale-en.js" type="text/javascript"></script>
        <script src="JS/jquery.jqGrid.min.js" type="text/javascript"></script>
    </head>
    <body>
        <div id="div1">
            <table id="tbl1" align="center">
                <tr>
                    <td colspan="2">
                        Employee ID:
                    </td>
                    <td colspan="2">
                        <input id="txtEmpId" type="text" />
                        &nbsp;
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        Employee Name:
                    </td>
                    <td colspan="2">
                        <input id="txtEmpName" type="text" />
                        &nbsp;
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        Password:
                    </td>
                    <td colspan="2">
                        <input id="txtPwd" type="text" />
                        &nbsp;
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        Confirm Password:
                    </td>
                    <td colspan="2">
                        <input id="txtCnfPwd" type="text" />
                        &nbsp;
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        Email:
                    </td>
                    <td colspan="2">
                        <input id="txtEmail" type="text" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <input id="btnInsert" type="button" value="Insert" />
                    </td>
                    <td>
                        <input id="btnShow" type="button" value="Show" />
                    </td>
                    <td>
                        &nbsp;<input id="btnDelete" type="button" value="Delete" onclick="DeleteEmployeeInfo();"/>
                    </td>
                    <td>
                        <input id="btnUpdate" type="button" value="Update"  onclick="UpdateEmployeeInfo();" />
                    </td>
                </tr>
            </table>
            <table id="tbl">
            </table>
            <div id="UsersGridPager">
            </div>
            <br />
        </div>
    </body>
    <script type="text/javascript">
       
        $(document).ready(function () {
            alert("New");
            $("#btnInsert").click(function () {
                $.ajax({
                    cache: false,
                    async: true,
                    type: "POST",
                    dataType: "json",
                    url: "http://localhost/DBWCFService/Service1.svc/InsertEmployeeDetails",
                    data: '{ "Emp_Id": "' + $("#txtEmpId").val() + '", "Emp_Name" : "' + $("#txtEmpName").val() + '", "Password" : "' + $("#txtPwd").val() + '", "Cnf_Password" : "' + $("#txtCnfPwd").val() + '", "Email" : "' + $("#txtEmail").val() + '"}',
                    contentType: "application/json;charset=utf-8",
                    success: function (r) { alert("Successfully Registered!!!"); },
                    error: function (e) { alert(e.statusText); }
                });
            });
    
        });
      
    
       
    
       // Get Employee Details
    
    
        $("#btnShow").click(function () {
            $.ajax({
                url: 'http://localhost/DBWCFService/Service1.svc/GetEmployees',
                async: false,
                type: "GET",
                datatype: "JSON"
            }).done(function (result) {
                if (result.length > 0) {
                    //for jqgrid
                    $("#tbl").jqGrid({
                        // data:
                        data: result,
                        datatype: "local",
                        contentType: "application/json; charset=utf-8;",
                        height: 'auto',
                        width: 760,
    
                        colNames: ['Actions', 'Employee Id', 'Employee Name', 'Password', 'Confirm Password', 'Email'],
                        colModel: [
                            { name: 'Actions', index: 'Actions', width: 75, sortable: false, align: 'center' },
                            { name: 'Emp_Id', index: 'Emp_Id', width: 100, editable: true, align: 'center' },
                            { name: 'Emp_Name', index: 'Emp_Name', width: 100, editable: true, align: 'center' },
                            { name: 'Password', index: 'Password', width: 100, editable: true, align: 'center' },
                            { name: 'Cnf_Password', index: 'Cnf_Password', width: 100, editable: true, align: 'center' },
                            { name: 'Email', index: 'Email', width: 100, editable: true, align: 'center' }
                        ],
                        rowNum: 10,
                        rowList: [10, 20, 30],
                        pager: '#UsersGridPager',
                        sortname: 'EmpId',
                        viewrecords: true,
                        sortorder: "desc",
                        gridComplete: function () {
                            var ids = jQuery("#tbl").jqGrid('getDataIDs');
                            for (var i = 0; i < ids.length; i++) {
                                var cl = ids[i];
                                be = "<input style='height:22px;width:20px;' type='button' value='E' onclick=\"jQuery('#tbl').editRow('" + cl + "');\" />";
                                se = "<input style='height:22px;width:20px;' type='button' value='S' onclick=\"jQuery('#tbl').saveRow('" + cl + "');\" />";
                                ce = "<input style='height:22px;width:20px;' type='button' value='C' onclick=\"jQuery('#tbl').restoreRow('" + cl + "');\" />";
                                jQuery("#tbl").jqGrid('setRowData', ids[i], { Actions: be + se + ce });
                            }
                        },
                        editurl: "http://localhost:53567/AdminGetEmployee.html",
                        caption: "Employee Details",
                        closeOnEscape: true //Closes the popup on pressing escape key
                    });
                }
    
                jQuery("#tbl").jqGrid('navGrid', "#UsersGridPager", { edit: false, add: false, del: false });
            });
        });
    
    
        // delete operation
        $(document).ready(function () {
            $("#btnDelete").click(function DeleteEmployeeInfo() {
                alert("delete function called");
                $("#txtEmpName").val("");
                $("#txtPwd").val("");
                $("#txtCnfPwd").val("");
                $("#txtEmail").val("");
                $.ajax({
                    type: "PUT",
                    url: "http://localhost/DBWCFService/Service1.svc/deleteEmployee/" + $("#txtEmpId").val(),
                    contentType: "application/json; charset=utf-8",
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status);
                        alert(xhr.statusText);
                        alert(thrownError)
                    },
                    success: function (response) {
                        alert("Successfully Deleted");
                    }
                });
            });
    
        });
    
        //Update Operation
    
    
        $(document).ready(function () {
            $("#btnUpdate").click(function UpdateEmployeeInfo() {
                var postParams = {};
                postParams["Emp_Id"] = $('#txtEmpId').val();
                postParams["Emp_Name"] = $('#txtEmpName').val();
                postParams["Password"] = $('#txtPwd').val();
                postParams["Cnf_Password"] = $('#txtCnfPwd').val();
                postParams["Email"] = $('#txtEmail').val();
    
                $.ajax({
                    type: "PUT",
                    url: "http://localhost/DBWCFService/Service1.svc/UpdateEmployee",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(postParams),
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.status);
                        alert(xhr.statusText);
                        alert(thrownError)
                    },
                    success: function (response) {
                        alert("Successfully Updated");
                    }
                });
            });
        });
    
            
    </script>
    </html>

    Getting 405, Method not allowed error for.. Delete And Update operations.. 

    It's working good for Inserting and Getting data to and fro from DB.

    Kindly, help me out with this "405, Method not allowed" error..

    Thank YOU, 

    Viswanath..

    Monday, October 27, 2014 12:26 PM

Answers

  • Hi,

    Based on the codes above, I noticed that you add the Method = "POST" prooperty for the UpdateEmployee method. You may need to use the [WebInvoke(Method = "PUT", ResponseFormat = WebMessageFormat.Json... for the update operation.

    HTTP Methods

    • GET - Requests a specific representation of a resource
    • PUT - Creates or update a resource with the supplied representation
    • DELETE - Deletes the specified resource
    • POST - Submits data to be processed by the identified resource

    For creating a REST service with WCF, you could refer to the following information:

    http://www.codeproject.com/Articles/182393/Create-a-REST-service-with-WCF-and-consume-it-usin

    Regards

    Tuesday, October 28, 2014 6:51 AM
    Moderator

All replies

  • Yes I got for Insert, Delete and Get Details...!

    Please, any one help me out from the above code for update operation.

    Tuesday, October 28, 2014 5:42 AM
  • Hi,

    Based on the codes above, I noticed that you add the Method = "POST" prooperty for the UpdateEmployee method. You may need to use the [WebInvoke(Method = "PUT", ResponseFormat = WebMessageFormat.Json... for the update operation.

    HTTP Methods

    • GET - Requests a specific representation of a resource
    • PUT - Creates or update a resource with the supplied representation
    • DELETE - Deletes the specified resource
    • POST - Submits data to be processed by the identified resource

    For creating a REST service with WCF, you could refer to the following information:

    http://www.codeproject.com/Articles/182393/Create-a-REST-service-with-WCF-and-consume-it-usin

    Regards

    Tuesday, October 28, 2014 6:51 AM
    Moderator