Get string from a class to web api - c#

I have a string in one class, I would like to get the string in my web api for the get request and add the value to my query. This is my code to get data from my Mysql database:
Web api
// GET: api/Blog
[HttpGet]
public List<BlogViews> Get()
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "SELECT * FROM test.blogtable where `Category` =" +;
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MSQLRD = cmd.ExecuteReader();
List<BlogViews> GetBlogList = new List<BlogViews>();
if (MSQLRD.HasRows)
{
while (MSQLRD.Read())
{
BlogViews BV = new BlogViews();
BV.id = (MSQLRD["id"].ToString());
BV.DisplayTopic = (MSQLRD["Topic"].ToString());
BV.DisplayMain = (MSQLRD["Summary"].ToString());
GetBlogList.Add(BV);
}
}
conn.Close();
return GetBlogList;
}
My Class
public class ItemsClass
{
public string id { get; set; }
public Entry IdEntry = new Entry{};
public Button DoneButton = new Button{};
public ItemsClass()
{
Content = new StackLayout
{
BackgroundColor = Color.FromHex("35ddcf"),
Padding = new Thickness(0, 50, 0, 10),
Children = { IdEntry,DoneButton }
};
}
private void DoneButton_Clicked(object sender, EventArgs e)
{
IdEntry.Text = id;
BlogContentsRestClient<BlogContentItemClass> restClient = new
BlogContentsRestClient<BlogContentItemClass>();
await restClient.GetAsync();
}
}
HttpRequest Class
public class BlogContentsRestClient<T>
{
private const string WebServiceUrl = "http://localhost:57645/api/BlogContents/";
public async Task<List<T>> GetAsync()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
}
Question
In my Web api Querystring Query = "SELECT * FROM test.blogtable where 'Category' =" +;. I would like to add the value of string id in ItemsClass, so that I can get data from my Mysql database.

I don't quite get what you mean by add the value of a class to your API method. ItemsClass is an object definition and not an instance of it. However you can provide your API method a parameter so that you have:
[HttpGet]
public List<BlogViews> Get(string id)
You can now call your API passing that parameter: /api/?id={insert here the id}
Alternatively you can call it in your request's body.
[HttpGet]
public List<BlogViews> Get([FromQuery, BindRequired] string id)
EDIT:
Check if this solution fits:
1) Use the method I posted before replacing this:
public List<BlogViews> Get()
with this:
public List<BlogViews> Get(string id)
2) Edit the GetAsync() method as follow:
// Added string id as parameter
public async Task<List<T>> GetAsync(string id)
{
// webUrl now become the same as WebServiceUrl but with parameter added
string webUrl = "http://localhost:57645/api/BlogContents/?id=" + id;
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(webUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
3) Edit the DoneButton_Clicked this way:
private void DoneButton_Clicked(object sender, EventArgs e)
{
IdEntry.Text = id;
BlogContentsRestClient<BlogContentItemClass> restClient = new
BlogContentsRestClient<BlogContentItemClass>();
await restClient.GetAsync(id); // Here you call the Get API with the id as parameter
}
4) Finally you can edit the query inside your Get(string id) method adding the id to the end:
string Query = "SELECT * FROM test.blogtable where `Category` =" + id;

Related

JSON Object Empty when is Serialize it C#?

I am using the following Code
public class GetTabelRealizari : ControllerBase
{
public class Realizare
{
String user;
String denumire;
String incasari;
public Realizare(String user, String denumire, String incasari)
{
this.user = user;
this.denumire = denumire;
this.incasari = incasari;
}
public String getUser()
{
return user;
}
public void setUser(String user)
{
this.user = user;
}
public String getDenumire()
{
return denumire;
}
public void setDenumire(String denumire)
{
this.denumire = denumire;
}
public String getIncasari()
{
return incasari;
}
public void setIncasari(String incasari)
{
this.incasari = incasari;
}
}
[HttpPost]
public string Post([FromBody] string[] value)
{
//SSMS connection
string connectionString = "Data Source=DESKTOP-QKC0G7V;Initial Catalog=Restaurant_gest;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
List<Realizare> realizari = new List<Realizare>();
double incasari;
String incasariString;
SqlCommand command = new SqlCommand("SELECT Users.Username," +
" Tip_Nota_Plata.Denumire," +
" sum(Nota_plata.Suma) as Incasari" +
" from Users" +
" INNER JOIN Nota_plata" +
" INNER JOIN Comandas" +
" ON Nota_plata.Id_comanda = Comandas.Id" +
" ON Comandas.User_Id = Users.Id" +
" INNER JOIN Tip_Nota_Plata" +
" ON Tip_Nota_Plata.Id = Nota_plata.Id_tip_nota" +
" Group by Username, Tip_Nota_Plata.Denumire", connection);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
incasari = (double)reader["Incasari"];
incasariString = incasari.ToString("#.##");
realizari.Add(new Realizare(reader["Username"].ToString(), reader["Denumire"].ToString(), incasariString));
}
}
return JsonConvert.SerializeObject(realizari);
//return "salut";
}
}
And I am receiving an empty JsonObject. Why?
[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]
I keep trying to make it work and I cannot. The list has the objects, i can test it with Console.Writeline(realizari[0].getDenumire()) and it works. I can also serialize a list of strings, it just doesn`t work for objects.
Because the object has no serializable properties.
I'm going to guess you are a Java developer based on this:
String user;
public String getUser()
{
return user;
}
public void setUser(String user)
{
this.user = user;
}
C# has "properties" which, while they compile down to methods very similar to this, the syntax in C# is a bit different. All of the above code can be simplified to a property:
public String User { get; set; }
The usage then becomes simpler as well, allowing for assignments instead of calling a method:
someObject.User = someUser;
In cases where you want to add logic to your getter/setter, you can expand the "auto implemented property" above into a manual one:
private string user;
public string User
{
get { return user; }
set { user = value; }
}
The get and set syntax still tells the compiler that this is a property, but within those blocks you can write any method logic you like. (In the setter value is a keyword for the value being assigned to the property.)

C# Unable to Get HTTP Return Codes via HttpResponseMessage

I’m getting an error in VS trying to check the Return Code of a method that builds and post data via an API.
The line that is generating the error is:
if (BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4) == MyGlobals.ReturnCode)
The error is:
Operator '==' cannot be applied to operands of type 'Task<string'>' and 'string'
My goal is to pass those parameters (data1, data5, etc) to the BuildApi() method and then post that data via an API call.
When the data is successfully posted, I should get a Return Code of 200 or a Return Code of 400 if an error occurred (according to the API developer).
The BuildApi() method should return either a 200 or 400 back to the condition statement.
Is the BuildApi() method formatted correctly to return the Return Code and if so, what’s wrong with that “if” statement?
Thanks in advance for your help!
Full Code:
static class MyGlobals
{
public static XmlDocument XmlAccounts = new XmlDocument();
public static XmlNode XmlRoot;
public static string data1 { get; set; }
public static string data2 { get; set; }
public static string data3 { get; set; }
public static string data4 { get; set; }
public static string data5 { get; set; }
public static string ReturnCode { get; set; }
}
static HttpClient client = new HttpClient();
static void Main(string[] args)
{
SqlConnection ObjConn = new SqlConnection();
string ConnectMe = #"
Data Source =SERVER;
Database =DATABASE1;
User ID =USER;
Pwd =PASS;
Connection Timeout =700
";
// Open Connection
ObjConn = new SqlConnection(ConnectMe);
ObjConn.Open();
// Call methods based on the required tool
SR_Provisioning(ObjConn);
}
static public void SR_Provisioning(SqlConnection ObjConn)
{
Get = #"
SELECT
data1,
data2,
data3,
data4,
data5
FROM
table
";
ObjAdp = new SqlDataAdapter(Get, ObjConn);
ObjAdp.Fill(OutputTable);
foreach (DataRow OutputRow in OutputTable.Rows)
{
//Initalize FQAN
string FQAN = "";
// Convert query output to variables
MyGlobals.data1 = OutputRow[0].ToString();
MyGlobals.data2 = OutputRow[1].ToString();
MyGlobals.data3 = OutputRow[2].ToString();
MyGlobals.data4 = OutputRow[3].ToString();
MyGlobals.data5 = OutputRow[4].ToString();
// Instantiate new objects
strFunctions MyStr = new strFunctions();
wshWin32API win32api = new wshWin32API();
// Convert server to FQDN for accessibility ease
string FQDN = getFQDN(MyGlobals.data1, ObjConn);
// Perform action based on Tranaction_Type
switch (MyGlobals.data5)
{
case "Add":
if (MyGlobals.data2 == "LOCAL")
{
// Create local ID first
try
{
FQAN = MyGlobals.data1 + "\\" + MyGlobals.data3;
// Check the return code to determine how to log the results
if (BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4) == MyGlobals.ReturnCode)
{
switch (MyGlobals.ReturnCode)
/*
Return Codes
200 (Created)
400(Expectation Failed)
*/
{
case "200":
// Do something
AllIsGood();
break;
case "400":
// Do something else
AllIsBad();
break;
}
}
}
catch (Exception err)
{
// Handle error and update transaction record
Update_Row();
}
}
}
static async Task<string> BuildApi(string data5, string data1, string FQAN, string data4)
{
try
{
UriBuilder baseUri = new UriBuilder("https://pwmfunction001.azurewebsites.net/api/VMGroupMemberModify01?code=T753ljF4jwXZXzmotCnnrBdV7Mrbqvcd3ibazRb92ZoBfJADuCpq5w==-Headers#{Metadata=true}-Body#{");
// Create the query string
string queryToAppend = "DATA5=" + data5 + ";DATA1=" + data1 + ";FQAN=" + FQAN + ";data4=" + data4 + "}";
if (baseUri.Query != null && baseUri.Query.Length > 1)
{
baseUri.Query = baseUri.Query.Substring(1) + ";" + queryToAppend;
}
else
{
// Check this
baseUri.Query = queryToAppend;
}
string httpResponseBody = "";
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(client.ToString());
HttpResponseMessage response = await client.PostAsync(baseUri.ToString(), content);
if (response.IsSuccessStatusCode)
{
httpResponseBody = "200";
return httpResponseBody;
}
else
{
httpResponseBody = "400";
return httpResponseBody;
}
}
catch(HttpRequestException err)
{
throw err;
}
}
}
}
Your BuildApi function is async so you need to await it in your code:
if (await BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4) == MyGlobals.ReturnCode)
UPDATE:
If you can't run it async then you need the result:
if (BuildApi(MyGlobals.data5, MyGlobals.data1, FQAN, MyGlobals.data4).Result == MyGlobals.ReturnCode)
However, I would try in the first instance to make your calling method async

C# reusing my interfaces for database access

I am relatively new to c# and have only been a developer for a couple years. I followed this really great tutorial on how to make a library with data models and interfaces to handle retrieving and inserting data into my database. I am working on a Blazor server side application. I utilize my data access library by injecting its interface onto the razor page via a service created in the startup.cs. All of this works fantastically.
However, Now I am making class that reads delimited files and inserts the data into the database table. I would like to use the same interfaces in my data access library that I use to connect my razor pages to the back end.
Here is my class where I want to use the InsertPermit method from IpermitData to insert a record to my database table but _db is null and will give me a null reference exception when I run it. How can I get a handle on this interface so I can use it to insert data?
{
public class TextFileParser
{
public TextFileParser()
{
}
public void InsertTextFileData(string filePath)
{
string errMessage = string.Empty;
FileInfo file = new FileInfo(filePath);
if (!File.Exists(file.FullName))
{
errMessage = "File not found!";
}
else if (file.Length >= 0)
{
errMessage = "File has no data!";
}
IPermitData _db;
PermitModel permitRecord = new PermitModel();
string vText = string.Empty;
string[] vString;
string delimiter = "\t";
StreamReader fileReader = new StreamReader(filePath);
List<PermitModel> dt = new List<PermitModel>();
//dt.Add("Parcel Number");
//dt.Columns.Add("Permit ID");
//dt.Columns.Add("Construction Loc");
//dt.Columns.Add("Submission Date");
//dt.Columns.Add("Issue Date");
//dt.Columns.Add("Permit Type");
//dt.Columns.Add("Const. Addr.");
//dt.Columns.Add("EST Cost");
//dt.Columns.Add("Referrer");
//dt.Columns.Add("Comments");
//dt.Columns.Add("Status");
int header = 1;
while (!fileReader.EndOfStream)
{
if (header == 1)
{
header += 1;
vText = fileReader.ReadLine();
vString = vText.Split(delimiter, StringSplitOptions.None);
continue;
}
vText = fileReader.ReadLine();
vString = vText.Split(delimiter, StringSplitOptions.None);
permitRecord.PD_ParcelID = vString[0];
permitRecord.PD_Situs1 = vString[1];
permitRecord.PD_Owner = vString[2];
permitRecord.PD_Addr1 = vString[3];
permitRecord.PD_Addr2 = vString[4];
permitRecord.ADDR_3 = vString[5];
permitRecord.PD_City = vString[6];
permitRecord.PD_State = vString[7];
permitRecord.PD_Zip = vString[8];
permitRecord.Type_Construction = vString[9];
permitRecord.Estimated_Cost = vString[10];
permitRecord.Permit_Issue_Date = vString[11];
permitRecord.Permit_Type = vString[12];
permitRecord.Property_Type = vString[13];
permitRecord.Permit_NO = vString[14];
permitRecord.Completion_Date = vString[15];
permitRecord.Percent_Complete = vString[16];
permitRecord.Modified_Date = vString[17];
permitRecord.Note = vString[18];
permitRecord.Note_Date = vString[19];
permitRecord.Submission_Date = vString[20];
permitRecord.Submitter = vString[21];
permitRecord.Submitter_Phone = vString[22];
permitRecord.Submitter_Email = vString[23];
permitRecord.Land_AV = vString[24];
permitRecord.Impr_AV = vString[25];
permitRecord.Sec_Location = vString[26];
try
{
_db.InsertPermit(permitRecord);
}
catch (Exception)
{
// dt.Add(vString[0], vString[14], vString[1], vString[20], vString[11], vString[12], vString[26], vString[10], vString[21], vString[18], "Failed " + ex.Message);
//dt.Add(permitRecord);
continue;
}
//dt.Rows.Add(vString[0], vString[14], vString[1], vString[20], vString[11], vString[12], vString[26], vString[10], vString[21], vString[18], "Passed");
}
}
}
}
Here are the code files from my dataaccesslibrary.
public interface IPermitData
{
Task<List<PermitModel>> GetPermitData();
Task InsertPermit(PermitModel permit);
Task DeletePermit(PermitModel permit);
}
public class PermitData : IPermitData
{
private readonly ISqlDataAccess _db;
public PermitData(ISqlDataAccess db)
{
_db = db;
}
public Task<List<PermitModel>> GetPermitData()
{
string sql = "select * from dbo.I_Permit";
return _db.LoadData<PermitModel, dynamic>(sql, new { });
}
public Task InsertPermit(PermitModel permit)
{
string sql = #"insert into dbo.I_Permit ( Parcel, Location, Owner_Name, ADDR_1, ADDR_2, ADDR_3, City, State_Sh, Zipcode, Type_Construction, Estimated_Cost, Permit_Issue_Date, Permit_Type, Property_Type, Permit_NO, Completion_Date, Percent_Complete, Modified_Date, Note, Note_Date, Submission_Date, Submitter, Submitter_Phone, Submitter_Email, Land_AV, Impr_AV, Sec_Location, PD_Owner, PD_Name2, PD_Addr1, PD_Addr2, PD_City, PD_State, PD_Zip, PD_ControlNo, PD_ParcelID, PD_Situs1, PD_Situs2, PD_S_City, PD_S_State, PS_S_Zip )
values ( #Parcel, #Location, #Owner_Name, #ADDR_1, #ADDR_2, #ADDR_3, #City, #State_Sh, #Zipcode, #Type_Construction, #Estimated_Cost, #Permit_Issue_Date, #Permit_Type, #Property_Type, #Permit_NO, #Completion_Date, #Percent_Complete, #Modified_Date, #Note, #Note_Date, #Submission_Date, #Submitter, #Submitter_Phone, #Submitter_Email, #Land_AV, #Impr_AV, #Sec_Location, #PD_Owner, #PD_Name2, #PD_Addr1, #PD_Addr2, #PD_City, #PD_State, #PD_Zip, #PD_ControlNo, #PD_ParcelID, #PD_Situs1, #PD_Situs2, #PD_S_City, #PD_S_State, #PS_S_Zip )";
return _db.SaveData(sql, permit);
}
public Task DeletePermit(PermitModel permit)
{
string sql = #"DELETE FROM dbo.I_Permit WHERE Record_ID =' " + permit.Record_ID + " ';";
return _db.DeleteData(sql, permit);
}
}
public interface ISqlDataAccess
{
string ConnectionStringName { get; set; }
Task<List<T>> LoadData<T, U>(string sql, U parameters);
Task SaveData<T>(string sql, T parameters);
Task DeleteData<T>(string sql, T parameters);
}
public class SqlDataAccess : ISqlDataAccess
{
private readonly IConfiguration _config;
public string ConnectionStringName { get; set; } = "Default";
public SqlDataAccess(IConfiguration config)
{
_config = config;
}
public async Task<List<T>> LoadData<T, U>(string sql, U parameters)
{
string connectionString = _config.GetConnectionString(ConnectionStringName);
using (IDbConnection connection = new SqlConnection(connectionString))
{
var data = await connection.QueryAsync<T>(sql, parameters);
return data.ToList();
}
}
public async Task SaveData<T>(string sql, T parameters)
{
string connectionString = _config.GetConnectionString(ConnectionStringName);
using (IDbConnection connection = new SqlConnection(connectionString))
{
await connection.ExecuteAsync(sql, parameters);
}
}
public async Task DeleteData<T>(string sql, T parameters)
{
string connectionString = _config.GetConnectionString(ConnectionStringName);
using (IDbConnection connection = new SqlConnection(connectionString))
{
await connection.ExecuteAsync(sql, parameters);
}
}
}
welcome to the community! The nice thing about .Net core is it makes the dependency injection system work very smoothly. So in your constructor for your parser, you just need to inject what you need from your data access layer. An example with your PermitData class would look like this:
public class TextFileParser
{
private IPermitData _permitData;
public TextFileParser(IPermitData permitData)
{
this._permitData= permitData;
}
// code that uses your injected service
_permitData.MethodToDoWorkEtc();
}
Notice that in the constructor you call for the interface you need as I have it written, but you can also call for a concrete class if that is how your dependency injection is set up. It then populates a backing field in your class with the injected service, and you use the backing field as the start point to do the work that needs done.
The DI framework will pick this all up when you build your app and assemble it for you, so as long as the service is registered in the Startup.cs file, you shouldn't need anything else. This method will also allow you to compose simple services together into larger more advanced services while keeping the simple parts separated for better testing and portability.
Hope this helps!

What's the proper way to set up a class to initialize public variables in c#?

I have created the class at the bottom in c#. This class is referenced by webservices to determine user accesses, like this:
[WebMethod]
public List<FAFSA> getFAFSA(string pageID)
{
formValues fv = new formValues();
string personID = fv.personID;
List<FAFSA> lf = new List<FAFSA>();
if (fv.secBlur == "no_secBlur")
{
FAFSA f = new FAFSA();
f.fafsaCheck = "0";
lf.Add(f);
}
...
}
I'm trying to add the two variables fafsa and staff. The method getSecBlur() is returning all three values from my database for secBlur, fafsa, and staff. So how do I set up this class, so that the SecBlur method is only called once but populates all three of my variables so that they can be used in webservice calls? It will not work the way it is now because it says fafsa and staff need to be static, but if I make them static, then in the webservices it says that the members must be accessed with an instance reference.
Sorry if this isn't worded to well, but I'm new to this and still trying to learn...
public class formValues : System.Web.Services.WebService
{
public string userName = getUserName();
public string firstName = getFirstName();
public string personID = getPersonID();
public int fafsa = 0;
public int staff = 0;
public string secBlur = getSecBlur();
private static string getUserDataString(int ix)
{
string retValue = "";
if (HttpContext.Current.Request.IsAuthenticated)
{
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
if (ticket != null)
{
string[] userData = { "" };
char[] delimiterChar = { '|' };
userData = ticket.UserData.Split(delimiterChar);
if (userData.Length > 1)
retValue = userData[ix];
else
{
FormsAuthentication.SignOut();
string redirUrl = "/DMC/loginNotFound.html";
HttpContext.Current.Response.Redirect(redirUrl, false);
}
}
}
}
return retValue;
}
private static string getUserName()
{
//This retrieves the person logged into windows/active directory
WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
//string[] fullUsername = wp.Identity.Name.Split('\\');
string fullUsername = wp.Identity.Name;
return fullUsername;
}
private static string getFirstName()
{
string firstName = getUserDataString(1);
return firstName;
}
private static string getPersonID()
{
string personID = getUserDataString(0);
return personID;
}
private static string getSecBlur()
{
string secBlur = "no_secBlur";
string mySQL = "exec get_UserAdminStatus #personID";
string cf = System.Configuration.ConfigurationManager.ConnectionStrings["DistrictAssessmentDWConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(cf);
SqlCommand command = new SqlCommand(mySQL, connection);
command.Parameters.AddWithValue("#personID", getUserDataString(0));
connection.Open();
SqlDataReader dr = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
connection.Close();
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["secBlur"].ToString() == "1")
secBlur = "secBlur";
fafsa = Convert.ToInt32(dt.Rows[0]["fafsa"]);
staff = Convert.ToInt32(dt.Rows[0]["staff"]);
}
return secBlur;
}
}
If you give any class static, public values the so called "Static" (or type) Constructor will be called to do the initialization work before any access is done: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
Another common way to do initlizsation or define default values, is to use the Factory Pattern. Afaik the Graphics Class in XNA has to adapt depending if you run ona X-Box or PC, so it uses the Factory Pattern.
Of coruse with Web(anything) there is the whole issue with variable Scope, even for Statics. Much less local variables.

How do I solve the System.NullReferenceException error

I just try to create one of WCF to get all client details. When I try to run that WCF which get data from SP its show this error:
Caught exception:
And also when put break point that time I see the ID is coming but still error showing same.
Class code:
public class CommanCall
{
string Connection = "Data Source=USER-PC\\SQLEXPRESS;Initial Catalog=BlueEyeNewDatabase;Integrated Security=True";
public List<Client> SelectAllClient(int id)
{
List<Client> ClientList = new List<Client>();
using (var Context = new EmpSystemContext(Connection))
{
var DbResult = Context.SelectClientDetails(id);
if (DbResult != null)
{
foreach (var Row in DbResult)
{
Client clist = new Client
{
ClientName = Row.ClientName,
ClientAddress = Row.ClientAddress,
PreferredCurrency = Row.PreferredCurrency,
FirstName = Row.FirstName,
LastName = Row.LastName,
City = Row.City,
State = Row.State,
Country = Row.Country,
PostalCode = Row.PostalCode,
ContactName = Row.ContactName,
ContactNumber = Row.ContactNumber,
Email = Row.Email,
ContactEmail = Row.ContactEmail
};
ClientList.Add(clist);
}
}
}
return ClientList;
}
}
Service.svc.cs
public class Service1 : IService1
{
public static EmpSystem.Domain.CommanCall Comman;
public ListResponce<Client> GetAllClientDetailsById(int id)
{
ListResponce<Client> lstclientResp = new ListResponce<Client>();
lstclientResp.Message = "Taru kai na thai ek record find na thayo";
lstclientResp.Success = false;
int id1 = id;
List<Client> lstclient = Comman.SelectAllClient(id);
lstclientResp.Result = lstclient;
if(lstclient!=null)
{
lstclientResp.Message = "Congo hahahhah Record Find thaya";
lstclientResp.Success = true;
}
return new ListResponce<Client>
{
Message = lstclientResp.Message,
Success = lstclientResp.Success,
Result = lstclientResp.Result
};
}
}
IService file
public interface IService1
{
[OperationContract]
[System.ServiceModel.Web.WebInvoke(Method = "GET", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, BodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped)]
ListResponce<Client> GetAllClientDetailsById(int id);
}
From the code you posted I can suggest you forgot to create an instance of CommanCall. Field Comman is reference type which is by default initialized with null. So NullReferenceException thrown when you trying to call member of null. Create an instance for Comman, for example:
public static EmpSystem.Domain.CommanCall Comman = new EmpSystem.Domain.CommanCall();
If field Comman initialized somewhere else, please, show stack trace of exception you caught.

Categories

Resources