locked
returning status and message from webservice method in c#.net RRS feed

  • Question

  • User1804579801 posted

    [WebMethod(EnableSession = false)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]//Specify return format.
    public string login(string UserName, string Password)
    {
    string Paravalue = "1";
    string status = "", message = "";
    List<master> listlogin = new List<master>();
    //LoginDetails = null;
    DataSet details = new DataSet();
    using (SqlConnection con = new SqlConnection(strConn))
    {
    SqlCommand cmd = new SqlCommand("App_Service", con);
    try
    {
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@Paravalue", Paravalue);
    cmd.Parameters.AddWithValue("@value", UserName);
    cmd.Parameters.AddWithValue("@value1", Password);
    cmd.Parameters.AddWithValue("@value2", "0");
    cmd.Parameters.AddWithValue("@value3", "0");
    //SqlParameter outputstatus = cmd.Parameters.Add("@status", SqlDbType.VarChar, 200);
    //outputstatus.Direction = ParameterDirection.Output;
    //SqlParameter outputstatus1 = cmd.Parameters.Add("@message", SqlDbType.VarChar, 200);
    //outputstatus1.Direction = ParameterDirection.Output;
    con.Open();
    SqlDataReader rdr = cmd.ExecuteReader();

    //status = outputstatus.Value.ToString();
    // message = outputstatus1.Value.ToString();
    while (rdr.Read())
    //if (LoginDetails.Rows.Count>0)
    {
    master login = new master();
    login.FullName = rdr["FullName"].ToString();
    login.username = rdr["UserName"].ToString();
    login.designation = rdr["designation"].ToString();
    login.device_token = rdr["device_token"].ToString();
    login.device_type = rdr["device_type"].ToString();
    login.vEmail = rdr["vEmail"].ToString();
    login.vName = rdr["vName"].ToString();
    login.vPhonenumber = rdr["vPhonenumber"].ToString();
    login.vDepartmentName = rdr["vDepartmentName"].ToString();
    login.iAdminId = rdr["iAdminId"].ToString();
    login.auth_key = rdr["auth_key"].ToString();
    login.vProfile_image = rdr["vProfile_image"].ToString();

    listlogin.Add(login);
    }
    cmd.Dispose();
    con.Close();
    con.Dispose();
    //throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message");


    }
    catch (Exception ex)
    {
    ExceptionLogging.SendErrorToText(ex);
    //Context.Response.StatusCode = ex.GetHashCode();
    status = ex.GetHashCode().ToString();
    message = ex.Message.ToString();
    throw new SoapException(ex.Message, SoapException.ServerFaultCode, Context.Request.Url.AbsoluteUri);
    //return message;
    }
    finally
    {
    cmd.Dispose();
    con.Close();
    con.Dispose();
    }
    }
    JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = 867530900 };
    //Context.Response.Write(js.Serialize(listlogin));
    return js.Serialize(listlogin);
    }

    when executed returns only 

    <string xmlns="http://tempuri.org/">
    [{"ProjectTypeId":0,"ProjectType":null,"ProjectTypeDescription":null,"Status":null,"TrainerId":0,"Userid":0,"username":"governmenttrainer","FullName":"Government Trainer","Password":null,"iTrainingId":0,"vTrainingName":null,"dStartdate":null,"dEnddate":null,"Address":null,"Mobile":null,"EmailId":null,"DOB":null,"TotalExperience":null,"vDistrict":null,"vState":null,"eTrainingMode":null,"TrainerName":null,"State":null,"City":null,"Experience":null,"Education":null,"designation":"designation","device_token":"device_token","device_type":"Anroid","vEmail":"vemail@email.com","vName":"Trainer Name","vPhonenumber":"9876543211","vDepartmentName":"Department","iAdminId":"iAdminId","auth_key":"8gw0440w4o0484sosk08kok0gw8cgkcogskw4ccc","vProfile_image":""}]
    </string>
    need  status and message 
    Monday, October 21, 2019 9:18 AM

Answers

  • User475983607 posted

    The following C# object model was generated from your JSON using Visual Studio.  Copy the JSON -> click Edit -> Paste Special -> Paste JSON as Classes.  You'll need to review the code generated types and assign a proper data type.

    public class Response
    {
        public int status { get; set; }
        public string message { get; set; }
        public string auth_key { get; set; }
        public Data data { get; set; }
    }
    
    public class Data
    {
        public string iAdminId { get; set; }
        public string vName { get; set; }
        public string vEmail { get; set; }
        public string vUserName { get; set; }
        public string vPassword { get; set; }
        public string vPhonenumber { get; set; }
        public string iGroupId { get; set; }
        public string dLastAccess { get; set; }
        public string eStatus { get; set; }
        public string iSysRecDeleted { get; set; }
        public string vDepartmentName { get; set; }
        public string vLogo { get; set; }
        public string vProfile_image { get; set; }
        public string vAddressline1 { get; set; }
        public string iCityId { get; set; }
        public string iStateId { get; set; }
        public string vPincode { get; set; }
        public string vLandline { get; set; }
        public string vResponsiblePersonName { get; set; }
        public string vRating { get; set; }
        public string iAgencyStateId { get; set; }
        public string iAgencyDistrictId { get; set; }
        public string tDescription { get; set; }
        public string vActivation_code { get; set; }
        public string vFacebookId { get; set; }
        public string vTrainingSpecialization { get; set; }
        public string vOrganizationType { get; set; }
        public string vFunctions { get; set; }
        public string vFullTimeEmployees { get; set; }
        public string vStateServed { get; set; }
        public string vWebsiteURL { get; set; }
        public string vUniqueCode { get; set; }
        public object vLatitude { get; set; }
        public object vLongtitude { get; set; }
        public object vDocuments { get; set; }
        public object vProvider { get; set; }
        public object vLocation { get; set; }
        public object iUpdatedby { get; set; }
        public object dUpdatedDate { get; set; }
        public string iAddedBy { get; set; }
        public string dAddedOn { get; set; }
        public string auth_key { get; set; }
        public string device_type { get; set; }
        public string device_token { get; set; }
        public string eApproved { get; set; }
        public string iApprovedBy { get; set; }
        public string dApprovedOn { get; set; }
        public object iDistrictId { get; set; }
        public string vCertificate { get; set; }
        public string vDateOfRegistration { get; set; }
        public string vTurnOverLastThirdyear { get; set; }
        public string vTurnOverLastSecondyear { get; set; }
        public string vTurnOverLastyear { get; set; }
        public string vCasetoCasePersons { get; set; }
        public string vEmpanelledPersons { get; set; }
        public string vFullTimePersons { get; set; }
        public string loginCount { get; set; }
    }

    You did not follow any of the previous advice and are still manually serializing the results and returning a collection.  

    nagapavanich

    But my other team requires status, message, and data in the format as explained above. Is it possible in webserive or do I need to look for web API? We can get the expected format when calling jquery ajax call. But our requriement is we will give a web service URL to my mobile app team who are expecting format as mentioned above. Please suggest iam on the right path or no.

    The problem is not Web Services.  Simply, you are not following the data contract established by your team.  IMHO, your code is a little sloppy.  @Value is the UserName and @Paravalue = 1 is required to return a result set.  The T-SQL should return one record given unique user credentials.  Perhaps there is a senior developer on your team that can help you.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 21, 2019 6:43 PM
  • User-719153870 posted

    Hi nagapavanich,

    master login = new master();
    master2 login2 = new master2();
    //master login1 = new master();
    login.status = "status:0,message:Welcome To KRC,auth_key:4go8c4k0g88ggg8w8ogcgokcggkks8044sc44wo0";
    login.data = "data:{";
    login.FullName = rdr["FullName"].ToString();
    login.username = rdr["UserName"].ToString();
    login.designation = rdr["designation"].ToString();
    login.device_token = rdr["device_token"].ToString();
    login.device_type = rdr["device_type"].ToString();
    login.vEmail = rdr["vEmail"].ToString();
    login.vName = rdr["vName"].ToString();
    login.vPhonenumber = rdr["vPhonenumber"].ToString();
    login.vDepartmentName = rdr["vDepartmentName"].ToString();
    login.iAdminId = rdr["iAdminId"].ToString();
    login.auth_key = rdr["auth_key"].ToString();
    login.vProfile_image = rdr["vProfile_image"].ToString();
    login.data = "}";

    I don't think this "login" will fit the expected response format, if you want your response has only four parameters and the fourth one will contain other several parameter, you should design your class following @mgebhard's suggestion which will require 2 classes.

    You can refer to below demo to change your code:

    public void login(string UserName, string Password)
            {
                string Paravalue = "1";
                string status = "0", message = "Welcome To KRC";
                List<Response> listlogin = new List<Response>();
                DataSet details = new DataSet();
                using (SqlConnection con = new SqlConnection(strConn))
                {
                    SqlCommand cmd = new SqlCommand("App_Service", con);
                    try
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@Paravalue", Paravalue);
                        cmd.Parameters.AddWithValue("@value", UserName);
                        cmd.Parameters.AddWithValue("@value1", Password);
                        cmd.Parameters.AddWithValue("@value2", "0");
                        cmd.Parameters.AddWithValue("@value3", "0");
                        con.Open();
                        SqlDataReader rdr = cmd.ExecuteReader();
                        while (rdr.Read())
                        {
                            Response res = new Response();
                            res.status = status;
                            res.message = message;
                            res.auth_key= rdr["auth_key"].ToString();
    
                            Data data = new Data();
                            data.auth_key= rdr["auth_key"].ToString();
                            data.iAdminId = "183";
                            data.vName= rdr["FullName"].ToString();
                            data.vEmail= rdr["UserName"].ToString();
                            data.vUserName= rdr["UserName"].ToString();
                            data.vPassword = "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92";
                            data.vPhonenumber= rdr["vPhonenumber"].ToString();
                            data.iGroupId = "8";
                            data.dLastAccess = "2019-09-16 01:09:30";
                            data.eStatus = "Active";
                            data.iSysRecDeleted = "0";
                            data.vDepartmentName = "";
                            data.vLogo = "";
                            data.vProfile_image = "";
                            data.vAddressline1 = "PMU Swajal Project First Floor Institute of Engineers India Building Dehradun Saharanpur Road Opposite ISBT Dehradun";
                            data.iCityId = "95";
                            data.iStateId = "3844";
                            data.vPincode = "248002";
                            data.vLandline = "0135-2643455";
                            data.vResponsiblePersonName = "";
                            data.vRating = "";
                            data.iAgencyStateId = "0";
                            data.iAgencyDistrictId = "0";
                            data.tDescription = "";
                            data.vActivation_code = "";
                            data.vFacebookId = "";
                            data.vTrainingSpecialization = "";
                            data.vOrganizationType = "";
                            data.vFunctions = "";
                            data.vFullTimeEmployees = "";
                            data.vStateServed = "";
                            data.vWebsiteURL = "";
                            data.vUniqueCode = "";
                            data.vLatitude = null;
                            data.vLongtitude = null;
                            data.vDocuments = null;
                            data.vProvider = null;
                            data.vLocation = null;
                            data.iUpdatedby = null;
                            data.dUpdatedDate = null;
                            data.iAddedBy = "0";
                            data.dAddedOn = "0000-00-00 00:00:00";
                            data.device_type = rdr["device_type"].ToString();
                            data.device_token = "123456";
                            data.eApproved = "Pending";
                            data.iApprovedBy = "0";
                            data.dApprovedOn = "0000-00-00 00:00:00";
                            data.iDistrictId = null;
                            data.vCertificate = "";
                            data.vDateOfRegistration = "";
                            data.vTurnOverLastThirdyear = "";
                            data.vTurnOverLastSecondyear = "";
                            data.vTurnOverLastyear = "";
                            data.vCasetoCasePersons = "";
                            data.vEmpanelledPersons = "";
                            data.vFullTimePersons = "";
                            data.loginCount = "0";
                            res.data = data;
    
                            listlogin.Add(res);
                        }
                        cmd.Dispose();
                        con.Close();
                        con.Dispose();
                    }
                    catch (Exception ex)
                    {
                        status = ex.GetHashCode().ToString();
                        message = ex.Message.ToString();
                        throw new SoapException(ex.Message, SoapException.ServerFaultCode, Context.Request.Url.AbsoluteUri);
                    }
                    finally
                    {
                        cmd.Dispose();
                        con.Close();
                        con.Dispose();
                    }
                }
                JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = 867530900 };
                Response.Write(js.Serialize(listlogin));
            }

    The Response and Data classes are from @mgebhard's post, and you will get below result:

    [{"status":"0","message":"Welcome To KRC","auth_key":"8gw0440w4o0484sosk08kok0gw8cgkcogskw4ccc","data":{"iAdminId":"183","vName":"Anil Kumar Purohit","vEmail":"anilkpurohit1970@gmail.com","vUserName":"anilkpurohit1970@gmail.com","vPassword":"8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92","vPhonenumber":"9876543211","iGroupId":"8","dLastAccess":"2019-09-16 01:09:30","eStatus":"Active","iSysRecDeleted":"0","vDepartmentName":"","vLogo":"","vProfile_image":"","vAddressline1":"PMU Swajal Project First Floor Institute of Engineers India Building Dehradun Saharanpur Road Opposite ISBT Dehradun","iCityId":"95","iStateId":"3844","vPincode":"248002","vLandline":"0135-2643455","vResponsiblePersonName":"","vRating":"","iAgencyStateId":"0","iAgencyDistrictId":"0","tDescription":"","vActivation_code":"","vFacebookId":"","vTrainingSpecialization":"","vOrganizationType":"","vFunctions":"","vFullTimeEmployees":"","vStateServed":"","vWebsiteURL":"","vUniqueCode":"","vLatitude":null,"vLongtitude":null,"vDocuments":null,"vProvider":null,"vLocation":null,"iUpdatedby":null,"dUpdatedDate":null,"iAddedBy":"0","dAddedOn":"0000-00-00 00:00:00","auth_key":"8gw0440w4o0484sosk08kok0gw8cgkcogskw4ccc","device_type":"Anroid","device_token":"123456","eApproved":"Pending","iApprovedBy":"0","dApprovedOn":"0000-00-00 00:00:00","iDistrictId":null,"vCertificate":"","vDateOfRegistration":"","vTurnOverLastThirdyear":"","vTurnOverLastSecondyear":"","vTurnOverLastyear":"","vCasetoCasePersons":"","vEmpanelledPersons":"","vFullTimePersons":"","loginCount":"0"}}]

    Best Regard,

    Yang Shen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 22, 2019 2:41 AM

All replies

  • User475983607 posted

    Please use common courtesy when posting content on the forum.  Use the "Insert/Edit Code Sample" button which looks like {;} when sharing codeUse the "Paste as text" button when posting formatted content from your browser or a Word processor.  Doing so makes you code and content much easier to read on the forum.  

    There are many logical issues and potential bugs with the shared code.  The login method serializes the results twice.  Always return the actual type rather than a string.  The .NET framework serializes the return type automatically.  There is not reason to serialize method results twice. 

    public master login(string UserName, string Password)
    {

    A login method should return a single item not a collection of logins.  Returning a collection should result in an exception. 

    You did not post the App_Service stored procedure.   The community cannot review this code.  IMO, the input parameters do no make sense for a login method.  However, it appear the stored procedure is returning results.   Several of the properties are populated which indicates the code is running but returning unexpected results.  You have not explained the expected results or how your code is intended to work.  The fact that a login method returned results commonly means the user is authenticated.  Can you explain how your code works?

    [
      {
        "ProjectTypeId": 0,
        "ProjectType": null,
        "ProjectTypeDescription": null,
        "Status": null,
        "TrainerId": 0,
        "Userid": 0,
        "username": "governmenttrainer",
        "FullName": "Government Trainer",
        "Password": null,
        "iTrainingId": 0,
        "vTrainingName": null,
        "dStartdate": null,
        "dEnddate": null,
        "Address": null,
        "Mobile": null,
        "EmailId": null,
        "DOB": null,
        "TotalExperience": null,
        "vDistrict": null,
        "vState": null,
        "eTrainingMode": null,
        "TrainerName": null,
        "State": null,
        "City": null,
        "Experience": null,
        "Education": null,
        "designation": "designation",
        "device_token": "device_token",
        "device_type": "Anroid",
        "vEmail": "vemail@email.com",
        "vName": "Trainer Name",
        "vPhonenumber": "9876543211",
        "vDepartmentName": "Department",
        "iAdminId": "iAdminId",
        "auth_key": "8gw0440w4o0484sosk08kok0gw8cgkcogskw4ccc",
        "vProfile_image": ""
      }
    ]

    I recommend starting with the basics.  Test the App_Service stored procedure using SQL Management Studio.  Verify the T-SQL is functioning as expected.  Run the code through the Visual Studio debugger.  Set a break point and single step through the code.  Verify the code is working as expected.

    Monday, October 21, 2019 11:40 AM
  • User1804579801 posted

    Dear mgebhard,

    Used the "Insert/Edit Code Sample" button while pasting my code but still displaying in normal text 

    SP: working as expected.

    ALTER PROCEDURE [dbo].[App_Service]
    (
    @Paravalue INT,
    @Value VARCHAR(150),
    @Value1 VARCHAR(4000),
    @Value2 VARCHAR(150),
    @Value3 VARCHAR(150)
    --@status   VARCHAR(200)OUTPUT,
    --@message VARCHAR(200)OUTPUT
    )
    AS
    BEGIN	 	 
    			DECLARE @COUNT INT
    	     	IF(@Paravalue = 1)
    			BEGIN
    				SELECT FullName,UserName,'designation' AS designation,'device_token' AS device_token, 'Anroid' AS device_type, 'vemail@email.com' AS vEmail, 'Trainer Name' AS vName, '9876543211' AS vPhonenumber, 'Department' AS vDepartmentName, 'iAdminId' AS iAdminId,'8gw0440w4o0484sosk08kok0gw8cgkcogskw4ccc' AS auth_key, '' AS vProfile_image
    				FROM Table_Login_Info AS T1 INNER JOIN Table_Lkp_Trainer_Details AS T2 ON T1.UserId = T2.UserId WHERE UserName = @Value
    				--SET @status = '0'
    				--SET @message = 'Welcome To KRC'
    				--SELECT @status
    			END
    			
    END
    			
    			


    We need the response in the below format for a mobile app 

    exected format :

    Response {
    "status": 0,
    "message": "Welcome To KRC",
    "auth_key": "4go8c4k0g88ggg8w8ogcgokcggkks8044sc44wo0",
    "data": {
    "iAdminId": "183",
    "vName": "Anil Kumar Purohit",
    "vEmail": "anilkpurohit1970@gmail.com",
    "vUserName": "anilkpurohit1970@gmail.com",
    "vPassword": "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
    "vPhonenumber": "9634240600",
    "iGroupId": "8",
    "dLastAccess": "2019-09-16 01:09:30",
    "eStatus": "Active",
    "iSysRecDeleted": "0",
    "vDepartmentName": "",
    "vLogo": "",
    "vProfile_image": "",
    "vAddressline1": "PMU Swajal Project First Floor Institute of Engineers India Building Dehradun Saharanpur Road Opposite ISBT Dehradun",
    "iCityId": "95",
    "iStateId": "3844",
    "vPincode": "248002",
    "vLandline": "0135-2643455",
    "vResponsiblePersonName": "",
    "vRating": "",
    "iAgencyStateId": "0",
    "iAgencyDistrictId": "0",
    "tDescription": "",
    "vActivation_code": "",
    "vFacebookId": "",
    "vTrainingSpecialization": "",
    "vOrganizationType": "",
    "vFunctions": "",
    "vFullTimeEmployees": "",
    "vStateServed": "",
    "vWebsiteURL": "",
    "vUniqueCode": "",
    "vLatitude": null,
    "vLongtitude": null,
    "vDocuments": null,
    "vProvider": null,
    "vLocation": null,
    "iUpdatedby": null,
    "dUpdatedDate": null,
    "iAddedBy": "0",
    "dAddedOn": "0000-00-00 00:00:00",
    "auth_key": "4go8c4k0g88ggg8w8ogcgokcggkks8044sc44wo0",
    "device_type": "ANDROID",
    "device_token": "123456",
    "eApproved": "Pending",
    "iApprovedBy": "0",
    "dApprovedOn": "0000-00-00 00:00:00",
    "iDistrictId": null,
    "vCertificate": "",
    "vDateOfRegistration": "",
    "vTurnOverLastThirdyear": "",
    "vTurnOverLastSecondyear": "",
    "vTurnOverLastyear": "",
    "vCasetoCasePersons": "",
    "vEmpanelledPersons": "",
    "vFullTimePersons": "",
    "loginCount": "0"
    }
    }

    [WebMethod(EnableSession = false)]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]//Specify return format.

    public void login(string UserName, string Password)
    {
    string Paravalue = "1";
    string status = "", message = "";
    List<master> listlogin = new List<master>();
    //LoginDetails = null;
    DataSet details = new DataSet();
    using (SqlConnection con = new SqlConnection(strConn))
    {
    SqlCommand cmd = new SqlCommand("App_Service", con);
    try
    {
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@Paravalue", Paravalue);
    cmd.Parameters.AddWithValue("@value", UserName);
    cmd.Parameters.AddWithValue("@value1", Password);
    cmd.Parameters.AddWithValue("@value2", "0");
    cmd.Parameters.AddWithValue("@value3", "0");
    //SqlParameter outputstatus = cmd.Parameters.Add("@status", SqlDbType.VarChar, 200);
    //outputstatus.Direction = ParameterDirection.Output;
    //SqlParameter outputstatus1 = cmd.Parameters.Add("@message", SqlDbType.VarChar, 200);
    //outputstatus1.Direction = ParameterDirection.Output;
    con.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    //SqlDataAdapter Dataadapt = new SqlDataAdapter(cmd);
    //DataTable dtlist = new DataTable();
    //Dataadapt.Fill(details);
    //LoginDetails = details.Tables[0];

    //status = outputstatus.Value.ToString();
    // message = outputstatus1.Value.ToString();
    while (rdr.Read())
    //if (LoginDetails.Rows.Count>0)
    {
    master login = new master();
    master2 login2 = new master2();
    //master login1 = new master();
    login.status = "status:0,message:Welcome To KRC,auth_key:4go8c4k0g88ggg8w8ogcgokcggkks8044sc44wo0";
    login.data = "data:{";
    login.FullName = rdr["FullName"].ToString();
    login.username = rdr["UserName"].ToString();
    login.designation = rdr["designation"].ToString();
    login.device_token = rdr["device_token"].ToString();
    login.device_type = rdr["device_type"].ToString();
    login.vEmail = rdr["vEmail"].ToString();
    login.vName = rdr["vName"].ToString();
    login.vPhonenumber = rdr["vPhonenumber"].ToString();
    login.vDepartmentName = rdr["vDepartmentName"].ToString();
    login.iAdminId = rdr["iAdminId"].ToString();
    login.auth_key = rdr["auth_key"].ToString();
    login.vProfile_image = rdr["vProfile_image"].ToString();
    login.data = "}";

    //login1.message = "Welcome To KRC";
    //login1.auth_key = "4go8c4k0g88ggg8w8ogcgokcggkks8044sc44wo0";
    //login2.status = "0";
    //login2.message = "Welcome To KRC";
    //login2.auth_key = "4go8c4k0g88ggg8w8ogcgokcggkks8044sc44wo0";
    //string[] str_add = { "status:0",
    // "message:Welcome To KRC",
    // "auth_key:4go8c4k0g88ggg8w8ogcgokcggkks8044sc44wo0" };
    //login.FullName = LoginDetails.Rows[0]["FullName"].ToString();
    //login.username = LoginDetails.Rows[0]["UserName"].ToString();
    //login.designation = LoginDetails.Rows[0]["designation"].ToString();
    //login.device_token = LoginDetails.Rows[0]["device_token"].ToString();
    //login.device_type = LoginDetails.Rows[0]["device_type"].ToString();
    //login.vEmail = LoginDetails.Rows[0]["vEmail"].ToString();
    //login.vName = LoginDetails.Rows[0]["vName"].ToString();
    //login.vPhonenumber = LoginDetails.Rows[0]["vPhonenumber"].ToString();
    //login.vDepartmentName = LoginDetails.Rows[0]["vDepartmentName"].ToString();
    //login.iAdminId = LoginDetails.Rows[0]["iAdminId"].ToString();
    //login.auth_key = LoginDetails.Rows[0]["auth_key"].ToString();
    //login.vProfile_image = LoginDetails.Rows[0]["vProfile_image"].ToString();
    //listlogin.Insert(0, login1);
    //listlogin.AddRange(str_add);

    listlogin.Add(login);
    }
    cmd.Dispose();
    con.Close();
    con.Dispose();
    //throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message");


    }
    catch (Exception ex)
    {
    ExceptionLogging.SendErrorToText(ex);
    //Context.Response.StatusCode = ex.GetHashCode();
    status = ex.GetHashCode().ToString();
    message = ex.Message.ToString();
    throw new SoapException(ex.Message, SoapException.ServerFaultCode, Context.Request.Url.AbsoluteUri);
    //return message;
    }
    finally
    {
    cmd.Dispose();
    con.Close();
    con.Dispose();
    }
    }
    JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = 867530900 };
    this.Context.Response.ContentType = "application/json; charset=utf-8";
    Context.Response.Write(js.Serialize(listlogin));
    //return js.Serialize(listlogin);
    }

    Now iam getting json format as

    [{"ProjectTypeId":0,"ProjectType":null,"ProjectTypeDescription":null,"status":"status:0,message:Welcome To KRC,auth_key:4go8c4k0g88ggg8w8ogcgokcggkks8044sc44wo0","data":"}","TrainerId":0,"Userid":0,"username":"governmenttrainer","FullName":"Government Trainer","Password":null,"iTrainingId":0,"vTrainingName":null,"dStartdate":null,"dEnddate":null,"Address":null,"Mobile":null,"EmailId":null,"DOB":null,"TotalExperience":null,"vDistrict":null,"vState":null,"eTrainingMode":null,"TrainerName":null,"State":null,"City":null,"Experience":null,"Education":null,"designation":"designation","device_token":"device_token","device_type":"Anroid","vEmail":"vemail@email.com","vName":"Trainer Name","vPhonenumber":"9876543211","vDepartmentName":"Department","iAdminId":"iAdminId","auth_key":"8gw0440w4o0484sosk08kok0gw8cgkcogskw4ccc","vProfile_image":""}]

    But my other team requires status, message, and data in the format as explained above. Is it possible in webserive or do I need to look for web API? We can get the expected format when calling jquery ajax call. But our requriement is we will give a web service URL to my mobile app team who are expecting format as mentioned above. Please suggest iam on the right path or no.

    Monday, October 21, 2019 1:48 PM
  • User475983607 posted

    The following C# object model was generated from your JSON using Visual Studio.  Copy the JSON -> click Edit -> Paste Special -> Paste JSON as Classes.  You'll need to review the code generated types and assign a proper data type.

    public class Response
    {
        public int status { get; set; }
        public string message { get; set; }
        public string auth_key { get; set; }
        public Data data { get; set; }
    }
    
    public class Data
    {
        public string iAdminId { get; set; }
        public string vName { get; set; }
        public string vEmail { get; set; }
        public string vUserName { get; set; }
        public string vPassword { get; set; }
        public string vPhonenumber { get; set; }
        public string iGroupId { get; set; }
        public string dLastAccess { get; set; }
        public string eStatus { get; set; }
        public string iSysRecDeleted { get; set; }
        public string vDepartmentName { get; set; }
        public string vLogo { get; set; }
        public string vProfile_image { get; set; }
        public string vAddressline1 { get; set; }
        public string iCityId { get; set; }
        public string iStateId { get; set; }
        public string vPincode { get; set; }
        public string vLandline { get; set; }
        public string vResponsiblePersonName { get; set; }
        public string vRating { get; set; }
        public string iAgencyStateId { get; set; }
        public string iAgencyDistrictId { get; set; }
        public string tDescription { get; set; }
        public string vActivation_code { get; set; }
        public string vFacebookId { get; set; }
        public string vTrainingSpecialization { get; set; }
        public string vOrganizationType { get; set; }
        public string vFunctions { get; set; }
        public string vFullTimeEmployees { get; set; }
        public string vStateServed { get; set; }
        public string vWebsiteURL { get; set; }
        public string vUniqueCode { get; set; }
        public object vLatitude { get; set; }
        public object vLongtitude { get; set; }
        public object vDocuments { get; set; }
        public object vProvider { get; set; }
        public object vLocation { get; set; }
        public object iUpdatedby { get; set; }
        public object dUpdatedDate { get; set; }
        public string iAddedBy { get; set; }
        public string dAddedOn { get; set; }
        public string auth_key { get; set; }
        public string device_type { get; set; }
        public string device_token { get; set; }
        public string eApproved { get; set; }
        public string iApprovedBy { get; set; }
        public string dApprovedOn { get; set; }
        public object iDistrictId { get; set; }
        public string vCertificate { get; set; }
        public string vDateOfRegistration { get; set; }
        public string vTurnOverLastThirdyear { get; set; }
        public string vTurnOverLastSecondyear { get; set; }
        public string vTurnOverLastyear { get; set; }
        public string vCasetoCasePersons { get; set; }
        public string vEmpanelledPersons { get; set; }
        public string vFullTimePersons { get; set; }
        public string loginCount { get; set; }
    }

    You did not follow any of the previous advice and are still manually serializing the results and returning a collection.  

    nagapavanich

    But my other team requires status, message, and data in the format as explained above. Is it possible in webserive or do I need to look for web API? We can get the expected format when calling jquery ajax call. But our requriement is we will give a web service URL to my mobile app team who are expecting format as mentioned above. Please suggest iam on the right path or no.

    The problem is not Web Services.  Simply, you are not following the data contract established by your team.  IMHO, your code is a little sloppy.  @Value is the UserName and @Paravalue = 1 is required to return a result set.  The T-SQL should return one record given unique user credentials.  Perhaps there is a senior developer on your team that can help you.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, October 21, 2019 6:43 PM
  • User-719153870 posted

    Hi nagapavanich,

    master login = new master();
    master2 login2 = new master2();
    //master login1 = new master();
    login.status = "status:0,message:Welcome To KRC,auth_key:4go8c4k0g88ggg8w8ogcgokcggkks8044sc44wo0";
    login.data = "data:{";
    login.FullName = rdr["FullName"].ToString();
    login.username = rdr["UserName"].ToString();
    login.designation = rdr["designation"].ToString();
    login.device_token = rdr["device_token"].ToString();
    login.device_type = rdr["device_type"].ToString();
    login.vEmail = rdr["vEmail"].ToString();
    login.vName = rdr["vName"].ToString();
    login.vPhonenumber = rdr["vPhonenumber"].ToString();
    login.vDepartmentName = rdr["vDepartmentName"].ToString();
    login.iAdminId = rdr["iAdminId"].ToString();
    login.auth_key = rdr["auth_key"].ToString();
    login.vProfile_image = rdr["vProfile_image"].ToString();
    login.data = "}";

    I don't think this "login" will fit the expected response format, if you want your response has only four parameters and the fourth one will contain other several parameter, you should design your class following @mgebhard's suggestion which will require 2 classes.

    You can refer to below demo to change your code:

    public void login(string UserName, string Password)
            {
                string Paravalue = "1";
                string status = "0", message = "Welcome To KRC";
                List<Response> listlogin = new List<Response>();
                DataSet details = new DataSet();
                using (SqlConnection con = new SqlConnection(strConn))
                {
                    SqlCommand cmd = new SqlCommand("App_Service", con);
                    try
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@Paravalue", Paravalue);
                        cmd.Parameters.AddWithValue("@value", UserName);
                        cmd.Parameters.AddWithValue("@value1", Password);
                        cmd.Parameters.AddWithValue("@value2", "0");
                        cmd.Parameters.AddWithValue("@value3", "0");
                        con.Open();
                        SqlDataReader rdr = cmd.ExecuteReader();
                        while (rdr.Read())
                        {
                            Response res = new Response();
                            res.status = status;
                            res.message = message;
                            res.auth_key= rdr["auth_key"].ToString();
    
                            Data data = new Data();
                            data.auth_key= rdr["auth_key"].ToString();
                            data.iAdminId = "183";
                            data.vName= rdr["FullName"].ToString();
                            data.vEmail= rdr["UserName"].ToString();
                            data.vUserName= rdr["UserName"].ToString();
                            data.vPassword = "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92";
                            data.vPhonenumber= rdr["vPhonenumber"].ToString();
                            data.iGroupId = "8";
                            data.dLastAccess = "2019-09-16 01:09:30";
                            data.eStatus = "Active";
                            data.iSysRecDeleted = "0";
                            data.vDepartmentName = "";
                            data.vLogo = "";
                            data.vProfile_image = "";
                            data.vAddressline1 = "PMU Swajal Project First Floor Institute of Engineers India Building Dehradun Saharanpur Road Opposite ISBT Dehradun";
                            data.iCityId = "95";
                            data.iStateId = "3844";
                            data.vPincode = "248002";
                            data.vLandline = "0135-2643455";
                            data.vResponsiblePersonName = "";
                            data.vRating = "";
                            data.iAgencyStateId = "0";
                            data.iAgencyDistrictId = "0";
                            data.tDescription = "";
                            data.vActivation_code = "";
                            data.vFacebookId = "";
                            data.vTrainingSpecialization = "";
                            data.vOrganizationType = "";
                            data.vFunctions = "";
                            data.vFullTimeEmployees = "";
                            data.vStateServed = "";
                            data.vWebsiteURL = "";
                            data.vUniqueCode = "";
                            data.vLatitude = null;
                            data.vLongtitude = null;
                            data.vDocuments = null;
                            data.vProvider = null;
                            data.vLocation = null;
                            data.iUpdatedby = null;
                            data.dUpdatedDate = null;
                            data.iAddedBy = "0";
                            data.dAddedOn = "0000-00-00 00:00:00";
                            data.device_type = rdr["device_type"].ToString();
                            data.device_token = "123456";
                            data.eApproved = "Pending";
                            data.iApprovedBy = "0";
                            data.dApprovedOn = "0000-00-00 00:00:00";
                            data.iDistrictId = null;
                            data.vCertificate = "";
                            data.vDateOfRegistration = "";
                            data.vTurnOverLastThirdyear = "";
                            data.vTurnOverLastSecondyear = "";
                            data.vTurnOverLastyear = "";
                            data.vCasetoCasePersons = "";
                            data.vEmpanelledPersons = "";
                            data.vFullTimePersons = "";
                            data.loginCount = "0";
                            res.data = data;
    
                            listlogin.Add(res);
                        }
                        cmd.Dispose();
                        con.Close();
                        con.Dispose();
                    }
                    catch (Exception ex)
                    {
                        status = ex.GetHashCode().ToString();
                        message = ex.Message.ToString();
                        throw new SoapException(ex.Message, SoapException.ServerFaultCode, Context.Request.Url.AbsoluteUri);
                    }
                    finally
                    {
                        cmd.Dispose();
                        con.Close();
                        con.Dispose();
                    }
                }
                JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = 867530900 };
                Response.Write(js.Serialize(listlogin));
            }

    The Response and Data classes are from @mgebhard's post, and you will get below result:

    [{"status":"0","message":"Welcome To KRC","auth_key":"8gw0440w4o0484sosk08kok0gw8cgkcogskw4ccc","data":{"iAdminId":"183","vName":"Anil Kumar Purohit","vEmail":"anilkpurohit1970@gmail.com","vUserName":"anilkpurohit1970@gmail.com","vPassword":"8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92","vPhonenumber":"9876543211","iGroupId":"8","dLastAccess":"2019-09-16 01:09:30","eStatus":"Active","iSysRecDeleted":"0","vDepartmentName":"","vLogo":"","vProfile_image":"","vAddressline1":"PMU Swajal Project First Floor Institute of Engineers India Building Dehradun Saharanpur Road Opposite ISBT Dehradun","iCityId":"95","iStateId":"3844","vPincode":"248002","vLandline":"0135-2643455","vResponsiblePersonName":"","vRating":"","iAgencyStateId":"0","iAgencyDistrictId":"0","tDescription":"","vActivation_code":"","vFacebookId":"","vTrainingSpecialization":"","vOrganizationType":"","vFunctions":"","vFullTimeEmployees":"","vStateServed":"","vWebsiteURL":"","vUniqueCode":"","vLatitude":null,"vLongtitude":null,"vDocuments":null,"vProvider":null,"vLocation":null,"iUpdatedby":null,"dUpdatedDate":null,"iAddedBy":"0","dAddedOn":"0000-00-00 00:00:00","auth_key":"8gw0440w4o0484sosk08kok0gw8cgkcogskw4ccc","device_type":"Anroid","device_token":"123456","eApproved":"Pending","iApprovedBy":"0","dApprovedOn":"0000-00-00 00:00:00","iDistrictId":null,"vCertificate":"","vDateOfRegistration":"","vTurnOverLastThirdyear":"","vTurnOverLastSecondyear":"","vTurnOverLastyear":"","vCasetoCasePersons":"","vEmpanelledPersons":"","vFullTimePersons":"","loginCount":"0"}}]

    Best Regard,

    Yang Shen

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 22, 2019 2:41 AM
  • User1804579801 posted

    thank a lot saved my day

    Tuesday, October 22, 2019 7:03 AM
  • User1804579801 posted

    thank a lot  Yang saved my day 

    Tuesday, October 22, 2019 7:04 AM
  • User1804579801 posted

    As said earlier in my post I need the data in curly braces but iam getting in [] that means iam getting data as JSON object but I need a string 

    I tried below 

    trail1 

    JavaScriptSerializer js = new JavaScriptSerializer() { MaxJsonLength = 867530900 };
    this.Context.Response.ContentType = "application/json; charset=utf-8";
    string JsonTraineeString = js.Serialize(listlogin);
    Context.Response.Write(JsonTraineeString); 

    [{"status":"0","message":"Welcome To KRC","auth_key":"4go8c4k0g88ggg8w8ogcgokcggkks8044sc44wo0","data":{"ProjectTypeId":0,"ProjectType":null,"ProjectTypeDescription":null,"status":null,"message":null,"TrainerId":0,"Userid":0,"username":"hydtrainer1","FullName":"Hyderabad Trainer one","Password":null,"iTrainingId":0,"vTrainingName":null,"dStartdate":null,"dEnddate":null,"Address":null,"Mobile":null,"EmailId":null,"DOB":null,"TotalExperience":null,"vDistrict":null,"vState":null,"eTrainingMode":null,"TrainerName":null,"State":null,"City":null,"Experience":null,"Education":null,"designation":"designation","device_token":"device_token","device_type":"Anroid","vEmail":"vemail@email.com","vName":"Trainer Name","vPhonenumber":"9876543211","vDepartmentName":"Department","iAdminId":"iAdminId","auth_key":"8gw0440w4o0484sosk08kok0gw8cgkcogskw4ccc","vProfile_image":""}}]

    I donot want [ ] brackets .Please suggest 

    trial II

    wanted to implement the nugate of url  

    https://www.softwaretestinghelp.com/create-json-objects-using-c/

    Installed nugate and checked with below code

    this.Context.Response.ContentType = "application/json; charset=utf-8";
    string JSONResult = JsonConvert.SerializeObject(listlogin);
    Context.Response.Write(JSONResult.ToString()); 

    still displays in json object 

    Tuesday, October 22, 2019 1:02 PM
  • User475983607 posted

    I donot want [ ] brackets .Please suggest 

    I have explained several times.   Do NOT return a collect!  Do NOT manually serialize the return type!  Simply return the actual type from the web method.

    public Response  login(string UserName, string Password)
    {
    

    It is up to you to fill a single type and return an error if more than one results set is returned from the stored procedure.  I still recommend meeting with a teammate or senior dev to help you write the code.  This should take a few minutes to fix.

    Tuesday, October 22, 2019 1:36 PM
  • User1804579801 posted

    Dear mgebhard,

    used the Replace string method  and solved it

    string JSONResult = JsonConvert.SerializeObject(listlogin);
    string FinalJsonstring1 = JSONResult.Replace("[", "");
    string FinalJsonstring2 = FinalJsonstring1.Replace("]", "");
    Context.Response.Write(FinalJsonstring2);

    Thank you for your support 

    Thursday, October 24, 2019 6:57 AM
  • User475983607 posted

    IMHO, this is a very poor design and I would fail this approach in a code review.  

    Thursday, October 24, 2019 11:01 AM
  • User1804579801 posted

    hI mgebhard,

    An android app is calling my c# webservice. In the HTTP header, there will be a token that I have to check each time my webservice is called in order to validate the identity of the caller.

    how can I achieve this . Please check the line of code iam trying to get a header. Iam on the right path. Please suggest. Ours is a small company there are no sr developer . As you said it is poor code in my earlier post. Please suggest me how can I improve my coding skills . Any URLs or any trainings 

    HttpContext.Current.Request.Headers.Get("auth_key");

    Thanks in advance 

    Thursday, October 31, 2019 10:49 AM