1

I am new to angularjs, I have created the HTML file and passed the controller to the RegistrationController.js, I created the Registration.cs file to store and retrieve the data from database. The problem is, i am not getting any errors, i am not getting the output, i could not able to identify the mistake that I have done in code.

RegisterController.js

    var app = angular.module("app", []) 
    app.controller("RegisterController", function ($scope, $http) {
        $scope.firstname = "";
        $scope.lastname = "";
        $scope.email = "";
        $scope.password = "";
        $scope.address = "";
        $scope.save = function () {
            var httpreq = {
                method: 'POST',
                url: 'http://localhost:50361/Registration.aspx',
                headers: {
                    'Content-Type':'application/json; charset=utf-8',
                    'dataType': 'json'
                },               
                data: {
                    firstname: $scope.firstname,
                    lastname: $scope.lastname,
                    email: $scope.email,
                    password: $scope.password,
                    address: $scope.address
                }
            };
            $http(httpreq).then(function (response) {

                alert("Registered Successfully");

            })
            .catch(function (error) {});
        }
    });

Registration.cs

public class Registration : System.Web.Services.WebService
{
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string email { get; set; }
    public string password { get; set; }
    public string address { get; set; }

    [WebMethod]
    public string InsertRegistration(string firstname, string lastname,
            string email, string password, string address)
    {
       NpgsqlConnection con = new NpgsqlConnection("Server=10.0.5.22;Port=5432;Database=TEST_DB;User Id=postgres;Password=test;");
        try
        {
            con.Open();
            NpgsqlCommand cmd = new NpgsqlCommand("insert into Registration1(FirstName,LastName,Email,Password,Address)values('" + firstname + "','" + lastname + "','" + email + "','" + password + "','" + address + "')", con);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            con.Close();
            return "Record Inserted Successfully";
        }
        }}
karthik shankar
  • 107
  • 2
  • 15
  • 1
    verify your URL url: 'App_Code/Registration.cs/InsertRegistration' , try to access to your WebService from some Browser – Mate Nov 28 '17 at 04:33
  • At very least you should be able to sort out if your client or server side code fails and update your post with true [MCVE]... (Also please *do not* post code with SQL injection issues as generally it distracts attention from your actual question and may bring implications that author of the code does not know how to write code) – Alexei Levenkov Nov 28 '17 at 05:04
  • As per @Mate's comment, your back end endpoint is likely to be `Registration.aspx/InsertRegistration` - i.e. never the `.cs` files. Please [parameterize your Query](https://stackoverflow.com/a/29352722/314291) - it's wide open to Sql Injection attacks. – StuartLC Nov 28 '17 at 06:22
  • 1
    @StuartLC: Should i create aspx file instead of this .cs?? and what about HTML file? do i have to write these front end also in aspx.html? – karthik shankar Nov 28 '17 at 06:27
  • @StuartLC: Can you help me with this RegistrationController.js? I did everything right but i think i made mistake in controller. i bind the data correctly.. but i am not getting the output as "Registered Successfully".. – karthik shankar Nov 28 '17 at 10:55

1 Answers1

2

When you create an asmx Web Service, you get two files:

  • an .asmx file which defines the endpoint
  • a .cs file which contains the 'code behind' and the WebMethod definitions.

Your ajax client must point to the .asmx endpoint, and not to the .cs file, e.g.

http://localhost/MyApp/Registration.asmx/InsertRegistration

In addition, there are a number of issues which I believe need to be pointed out:

  • You'll need to decorate the service with [System.Web.Script.Services.ScriptService] in order to use it with Ajax.
    • In any event .asmx Web Services are legacy technology (they were for xml SOAP) - for exposing RESTful services for use with modern front ends like Angular, you should be using Asp.net WebApi 2 or later.
    • Do not use string concatenation to bind variables to a SqlCommand - this leaves your database open to SqlInjection attacks. Parameterize them like I've done above
    • Do not store passwords in clear text. Add a salt and hash many times
    • With Postgres, be very careful about casing - PostGres is case sensitive, but only if you wrap identifiers in double quotes ("), so it's usually safer to use lower case throughout.
    • You've missed out on your catch or finally statement to balance your try
    • It's safer to wrap Disposables like SqlCommand and SqlConnection in a using block
    • Unless your web service is stateful (which isn't a scaleable idea), you should't have publically accessible properties public string firstname { get; set; } etc. - these aren't needed in your registration and conflict with the parameters passed.

The final WebMethod .cs would look more like so:

[System.Web.Script.Services.ScriptService]
public class Registration : WebService
{
    [WebMethod]
    public string InsertRegistration(string firstname, string lastname,
                string email, string password, string address)
    {
        try
        {
            using (var con = new NpgsqlConnection(
         "Server=127.0.0.1;Port=5432;Database=TEST_DB;User Id=user;Password=password;"))
            using (var cmd = new NpgsqlCommand(
       "insert into public.registration1(firstname, lastname, email, passwordhash, address)"
             + " values (@firstName, @lastName, @email, @passwordhash, @address);", con))
            {
                con.Open();
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@firstName", firstname);
                cmd.Parameters.AddWithValue("@lastName", lastname);
                cmd.Parameters.AddWithValue("@email", email);
                cmd.Parameters.AddWithValue("@passwordhash", HashMyPassword(password));
                cmd.Parameters.AddWithValue("@address", address);
                cmd.ExecuteNonQuery();
            }
            return "Record Inserted Successfully";
        }
        catch (Exception)
        {
            return "Failed";
        }
    }

    public static string HashMyPassword(string unhashed)
    {
       // use a decent hashing algo like PBKDF2 or scrypt
    }
}

And the associated endpoint markup file, Registration.asmx is simply

<%@ WebService Language="C#" CodeBehind="Registration.asmx.cs" Class="MyNameSpace.Registration" %>
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • 1
    Thank you for your valuable time you gave to help me. I followed the above steps. Now i created as like of your tips. The main problem is i could not able to connect between controller and the aspx.cs file using Ajax. – karthik shankar Nov 28 '17 at 08:20
  • Build your back end WebService code, open the above WebMethod code and then debug run (F5). Visual Studio should open up a browser window at the WebMethod URL above, with the `WSDL` navigation pages. You can then copy the url to use with Ajax from there (without any wsdl querystring or stub) – StuartLC Nov 28 '17 at 08:27
  • @karthikshankar - I'll only be back in front of a PC in 12 hours time. If you are strugging with Angular, why not just try a simple Fiddler, Postman or even jQuery `$.post()` example just to ensure the back end is working, and then you can debug Angular's Ajax call – StuartLC Nov 28 '17 at 11:05
  • 1
    Okay Stuart i will try in that way. – karthik shankar Nov 28 '17 at 11:21
  • please go through it if you are free. https://stackoverflow.com/questions/47588420/unable-to-display-data-from-the-database-into-html-table-using-angularjs-and-asp – karthik shankar Dec 01 '17 at 07:26