How to create a json in API? - c#

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)

Related

c# Query sqlite database, get back a data with a type

I am encountering some issues when it comes to getting back data from my c# database query
this is my code for the query :
using System;
using System.Text;
using System.Data;
using System.Data.SQLite;
namespace Cryptomoney
{
class DataClass
{
private static SQLiteConnection sqlite;
public DataClass()
{
sqlite = new SQLiteConnection("Data Source= DataCrypto.sqlite3;Version=3;New=False;");
}
public SQLiteDataReader SelectQuery(string query)
{
try
{
sqlite.Open(); //Initiate connection to the db
SQLiteCommand sqlComm = sqlite.CreateCommand();
sqlComm.CommandText = query;
SQLiteDataReader r = sqlComm.ExecuteReader();
sqlite.Close();
}
catch (SQLiteException ex)
{
Console.WriteLine(ex);
}
sqlite.Close();
return r;
}
}
}
and this is the code with the sql :
var b = dataClass.SelectQuery("SELECT PercChange1h FROM DataCrypt WHERE ID = 1");
I want b to be a float, the same type as PercChange1h is in my database but I only get "System.Data.SQLite.SQLiteDataReader".
I already tried :
var b = (float)dataClass.SelectQuery("SELECT PercChange1h FROM DataCrypt WHERE ID = 1")["PercChange1h"]
which returns an error "row does not exist". And all other types of casts do not work ((int), ToString())
My code is nearly the same with create or ALTER or INSERT and it works just fine (but I do not have to get back data"
var cmd = new SQLiteCommand();
cmd = sqlite.CreateCommand();
cmd.CommandText = query; //set the passed query
cmd.ExecuteNonQuery();
Do you know how I could get back a type like string or float from my sqlite db with c# ?
(this is my first question ever so if there is not enough data, I am here to answer)
Have a nice day!
Your function should look like this
public object QueryScalarValue(string query)
{
try
{
sqlite.Open(); //Initiate connection to the db
using(SQLiteCommand sqlComm = new SQLiteCommand(query, sqlite))
return sqlComm.ExecuteScalar();
}
catch (SQLiteException ex)
{
Console.WriteLine(ex);
}
finally
{
sqlite.Close();
}
return r;
}
Then you simply cast the result
var b = (double)dataClass.SelectQuery("SELECT PercChange1h FROM DataCrypt WHERE ID = 1");

Call a method in another class from a CSHTML file

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();

How Do I Use C# Code In HTML To Get ID Out Of A SQL Database?

So I'm trying to create a website with a database and currently just wanting to check the database connnection by printing a number from the database in the HTML code. I'm terrible at scripts so please ignore that.
The C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class LogFiller
{
public int userID;
string connectionstring = "USER ID=x;" +
"PASSWORD=x;server=x;" +
"Trusted_Connection=yes;" +
"database=x; " +
"connection timeout=30";
public LogFiller()
{
//
// TODO: Add constructor logic here
//
}
public int getUserID
{
get {
using (var connection = new SqlConnection(connectionstring))
{
try
{
connection.Open();
SqlCommand myCommand = new SqlCommand("SELECT ID FROM x WHERE Name = 'x'", connection);
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
adapter.Fill(dt);
return (int)dt.Rows[0][0];
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
return userID;
}
}
}
The script I thought of (but doesn't work)
#{
LogFiller lf = new LogFiller();
lf.getUserID;
}
For clarification: I want to just write the number that the C# code returns anywhere on my page.
Once you open a C# block with the #{ }, in order to write the value from a variable inside that block you need to escape it with another # like this:
#{
LogFiller lf = new LogFiller();
<p>User ID: #lf.getUserID</p>
}
Also, as someone in a comment stated, you'll likely need to fully qualify your LogFiller type with the namespace. So WhateverYourNamespaceIs.LogFiller

can't access my new class in c# (webb-app)

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.

Display query result depending on user input

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)

Categories

Resources