I am working on a code in C#.NET to create a web service that will take in a particular input. It will then connect to the database , where depending on the input provided, the entire result must be fetched from my table and displayed accordingly.
However, I am not that familiar with C#.NET and so I am not able to implement my code properly. can someone please help me
Here is what I have do so far:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace test3
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public String GetAttendance(String rollno)
{
String result="";
try
{
using (SqlConnection myConnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123"))
{
myConnection.Open();
using (SqlCommand myCommand = new SqlCommand())
{
myCommand.Connection = myConnection;
myCommand.CommandText = "SELECT COUNT(*) FROM studentdata WHERE rollno = #rollno";
myCommand.Parameters.Add("#rollno", SqlDbType.VarChar).Value = rollno;
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
result = myReader.ToString();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "an error occured";
}
return result;
}
}
}
If I run this code, I get output as "System.Data.SqlClient.SqlDataReader" which is not what i want
Don't use a data reader for this you only have one result which is a row count so use ExecuteScalar() and use an int as type for result:
int result = Convert.ToInt32(myCommand.ExecuteScalar());
(Alternatively you can get the string value with your current query using result = myReader.GetInt32(0).ToString(); - don't do this though)
Related
My first API and my first JSON
I want to convert results from SQL Query
I want to put the results in a JSON so when users call the API they get a JSON text to consume.
I found this question here that help
How to use SqlCommand and SqlDataReader to return a Json result in C#
but when I try to apply the same in my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;
namespace CDAPIs.Controllers
{
public class RepsSelect : ApiController
{
string gDBConn = "Data Source=Server;Database=DB1;User Id=user;Password=*******;";
[Route("api/RepsSelect/{RepID}/{Tag}")]
public string Get(string RepID, string Tag)
{
SqlConnection conn = new SqlConnection(gDBConn);
SqlCommand cmd = new SqlCommand("RepsSelect", conn);
cmd.CommandTimeout = 0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#RepID", RepID));
cmd.Parameters.Add(new SqlParameter("#Tag", ""));
try
{
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
var dt = new DataTable();
dt.Load(rdr);
List<DataRow> result = dt.AsEnumerable().ToList();
rdr.Close();
// Error is here
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
var error = ex.Message;
return View(error);
}
}
}
}
I get these errors
CS1503 : Argument 2: cannot convert from "System.Web.Mvc.JsonRequestBehavior" to "Newtonsoft.Json.JsonSerializedSettings"
I tried using Newtonsoft.Json instead of System.Web.Mvc but I got this error
When working with APIs - we want to work with the http response protocol (best practice).
Try changing this
public HttpResponseMessage Get(string RepID, string Tag)
and then
return Request.CreateResponse(HttpStatusCode.OK, result, Configuration.Formatters.JsonFormatter);
In the catch block you will want to return
Request.CreateErrorResponse(HttpStatusCode.NotFound, "Data Not Found");
Kia Kaha asmgx,
Mike Smith
you need to change
[Route("api/RepsSelect/{RepID}/{Tag}")]
public string Get(string RepID, string Tag)
to
[Route("api/RepsSelect/{RepID}/{Tag}")]
public JsonResult Get(string RepID, string Tag)
I'm new in ASP.Net development, and facing problem in sending data from webService to webform. I'm using JSON method,but in following line of code I'm having issue. The compiler shows this error message.
"Error 3 Invalid token '(' in class, struct, or interface member
declaration
Can someone tell me what is the problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting;
/// <summary>
/// Summary description for GetStudent
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class GetStudent : System.Web.Services.WebService {
[WebMethod]
public GetStudent () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void GetStudent () {
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Documents\\Visual Studio 2012\\WebSites\\WebSite1\\App_Data\\Database.mdf';Integrated Security= True");
List<StudentsList> stu = new List<StudentsList>();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From Student";
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
StudentsList student = new StudentsList();
student.Id = Convert.ToInt32(DR["Id"]);
student.name = DR["name"].ToString();
student.fname = DR["fname"].ToString();
student.email = DR["email"].ToString();
student.contact = DR["contact"].ToString();
student.Pname = DR["Pname"].ToString();
student.Cname = DR["Cname"].ToString();
StudentsList.Add(student);
}
JavaScriptSerializer js = new JavaScriptSerializer(StudentsList());
Context.Response.Write(js.Serializ(StudentsList));
}
}
Here is how you need to fix your GetStudent method -
[WebMethod]
public void GetStudent () {
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Documents\\Visual Studio 2012\\WebSites\\WebSite1\\App_Data\\Database.mdf';Integrated Security= True");
List<StudentsList> stu = new List<StudentsList>();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From Student";
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
StudentsList student = new StudentsList();
student.Id = Convert.ToInt32(DR["Id"]);
student.name = DR["name"].ToString();
student.fname = DR["fname"].ToString();
student.email = DR["email"].ToString();
student.contact = DR["contact"].ToString();
student.Pname = DR["Pname"].ToString();
student.Cname = DR["Cname"].ToString();
stu.Add(student); //Changed line: Changed variable name to stu which is the list variable declared earlier.
}
JavaScriptSerializer js = new JavaScriptSerializer(); //changed line : Removed the invalid parameter to the constructor of JavaScriptSerializer class
Context.Response.Write(js.Serializ(stu)); //changed line : Used the correct stu list variable declared at the starting of the method.
}
Note: Please follow extreme caution while naming your class. Your StudentList entity isn't a list but an individual student entity with various properties like Id,name,fname etc. Please consider renaming it to Student.
In order to validate that you aren't getting any invalid characters from your database first try running if below code works fine or not?
class Program
{
static void Main(string[] args)
{
List<StudentsList> stu = new List<StudentsList>();
StudentsList student = new StudentsList();
student.name = "Abdul Basit Mehmood";
student.fname = "Abdul";
stu.Add(student);
JavaScriptSerializer js = new JavaScriptSerializer();
var serializedValue = js.Serialize(stu);
}
}
class StudentsList
{
public string name;
public string fname;
}
serializedValue variable should show you a valid JSON string in quick watch window as shown below:
I have searched everywhere but cannot figure out what is wrong here. I have a webb c# app. I have a c# method in the app folder where I query a database and then want to pass that value back to my Cshtml page where I will be makin deciaions based on the value. No matted what I do, when I call the method and then try to read the value I get the error "Cannot implicitly convert type 'class1' to string.
Here is my c#class method and below the calls
Method:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public class class1
{
public static string getdata()
{
string cnnString = ConfigurationManager.ConnectionStrings["GDC_WellsFargoConnectionString"].ConnectionString;
SqlDataReader reader;
string returnValue;
/// var cmd = "insert into Email Insert values(#name,#email";
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand("Select isnull([Authorization],'none') as authoriztion from PNSWebAuthorization where username = '" + userName + "'", cnn))
{
////cmd.Parameters.AddWithValue("#name", "Newname,First");
//// cmd.Parameters.AddWithValue("#email", "Newemail#gibsondunn.com");
///string authcode;
cnn.Open();
try {
reader = cmd.ExecuteReader();
if (reader.Read())
{
returnValue = reader["Authorization"].ToString();
reader.Close();
return returnValue;
}
else
{
reader.Close();
return "";
}
}
catch (Exception err)
{
throw new ApplicationException(err.Message);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
}
}
CSHTML Calling
#model GDC.Finance.WebClient.Areas.Treasury.ViewModels.CashReceiptSessionListViewModel
#using PagedList.Mvc;
#{
ViewBag.Title = "Cash Receipt Sessions test";
}
<h2>Sessions</h2>
#section scripts{
<script src="~/Scripts/popup.js"></script>
}
#{
/// string auth = "none";
var auth = new class1();
class1.getdata();
string rights = auth;
}
Auth throws the error.
Looks like "public static string getdata()" is a static method.
why not try calling it this way:
var auth = class1.getdata();
Hello i am learning to program but currently i am stuck.
When i add this class directly in to the file that should be using the class, it works.
When i place this class en in a seperate .cs file, i can't seem to use it.
This is my DAL class for accessing my database (very basic)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// Summary description for DAL
/// </summary>
public class DAL
{
// We valideren de gegevens die de gebruiker ingeeft met de gegevens in de database.
public static bool CheckUser(string username, string password)
{
DataTable result = null;
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RTIdb"].ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Wachtwoord FROM Gebruikers Where GebruikersNaam = #uname";
cmd.Parameters.Add(new SqlParameter("#uname", username));
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
result = new DataTable();
da.Fill(result);
}
if (password.Trim() == result.Rows[0]["Wachtwoord"].ToString().Trim())
{
// Als we hier geraken zijn de ingevoerde gebruikersnaam en wachtwoord correct
return true;
}
}
}
}
catch (Exception ex)
{
// problem handling
}
// gebruikersnaam niet gevonden
return false;
}
public static string GetWeergaveNaam(string username)
{
DataTable result = null;
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RTIdb"].ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT WeergaveNaam FROM Gebruikers WHERE GebruikersNaam = #uname";
cmd.Parameters.Add(new SqlParameter("#uname", username));
using (SqlDataAdapter da = new SqlDataAdapter())
{
result = new DataTable();
da.Fill(result);
}
if (result.Rows.Count == 1)
{
return result.Rows[0]["WeergaveNaam"].ToString().Trim();
}
}
}
}
catch (Exception)
{
// TODO opvangen exception
}
return "SQL ERROR";
}
// Nu moeten we de rol van de gebruiker nog opzoeken
public static string GetUserRoles(string username)
{
DataTable result = null;
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RTIdb"].ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Roles FROM Gebruikers WHERE GebruikersNaam = #uname";
cmd.Parameters.Add(new SqlParameter("#uname", username));
using (SqlDataAdapter da = new SqlDataAdapter())
{
result = new DataTable();
da.Fill(result);
}
if (result.Rows.Count == 1)
{
return result.Rows[0]["Roles"].ToString().Trim();
}
}
}
}
catch (Exception ex)
{
// exception handling
}
// user id not found, dus is hij een gast
return "guest";
}
}
now when i want to access these methods in a different file like
DAL.CheckUser(username, password);
then i get an error in visual studio saying : "The name 'DAL' does not exist in the current context"
I would assume it hase something todo with namespaces, but i don't have any namespaces declared in any file. Whe i do add the "namespace" declaration, it does not find the namespace in my second file... so in other words i am stuck :-s
I hope someone can send me in the right direction...
Please check again about using namespace keyword of your project. I compiled successfully with two classes on two files in two difference folders.
File Business.cs in project folder
public class Business
{
public void TestFunc()
{
DAL.TestFunction();
}
}
File DAL.cs in DAL folder
public class DAL
{
public static void TestFunction()
{
//Do something
}
}
Your class isn't inside a namespace.
To refer to a class that isn't inside a namespace you should use:
global::DAL.CheckUser(username, password);
Be aware, it's a bad practice not declaring namespaces.
There are 2 options for namespacing in here:
1) You can declare both files in the same namespace;
2) You can declare both files in different namespaces and declare a using command in the file which needs to refer to the other namespace.
Namespaces group your classes in logical groups. Usually the location of the class in the folder structure of the project is used. Files in 1 namespace can call the protected and public members of each others without a using command. Files in different namespaces need to make an explicit using reference to the other namespace.
I have defined a function in following class like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using MFDBAnalyser;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
namespace MFDBAnalyser
{
public class PrimaryKeyChecker : IMFDBAnalyserPlugin
{
public string RunAnalysis(string ConnectionString)
{
return GetAllPrimaryKeyTables(ConnectionString);
}
/// <summary>
/// This function populates the tables with primary keys in a datagrid dgResultView.
/// </summary>
/// <param name="localServer"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="selectedDatabase"></param>
/// <returns></returns>
public string GetAllPrimaryKeyTables(string ConnectionString)
{
string result = string.Empty;
// Query to select primary key tables.
string selectPrimaryKeyTables = #"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
// put your SqlConnection and SqlCommand into using blocks!
using(SqlConnection sConnection = new SqlConnection(ConnectionString))
using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfPrimaryKeyTables);
using(StringWriter sw = new StringWriter())
{
dtListOfPrimaryKeyTables.WriteXml(sw);
result = sw.ToString();
}
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return result;
}
}
}
But when I am calling this like this
protected void GetPrimaryKeyTables()
{
DataTable dtPrimaryKeys = new PrimaryKeyChecker().GetAllPrimaryKeyTables(txtHost.Text, txtUsername.Text, txtPassword.Text, Convert.ToString(cmbDatabases.SelectedValue));
dgResultView.DataSource = dtPrimaryKeys;
}
Then it is throwing errors like
Error 1 The type or namespace name
'PrimaryKeyChecker' could not be found
(are you missing a using directive or
an assembly
reference?) D:\Projects\Mindfire\GoalPlan\MFDBAnalyser\MFDBAnalyser\MFDBAnalyser.cs 340 43 MFDBAnalyser
You didn't show what using statements are in effect for GetPrimaryKeyTables() but you can always use the full name:
DataTable dtPrimaryKeys =
new MFDBAnalyser.PrimaryKeyChecker().GetAllPrimaryKeyTables(...));
I suspect you may have misspelled one instance of MFDBAnalyser
If the class that defines GetPrimaryKeyTables() method is not in the MFDBAnalyser namespace, you will need to include using statement at the top of that file, like so...
using MFDBAnalyser;
Alternatively, you could instantiate PrimaryKeyChecker using its full name, like so...
DataTable dtPrimaryKeys = new PrimaryKeyChecker().GetAllPrimaryKeyTables(...);