Call a method in another class from a CSHTML file - c#

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

Related

How to create a json in API?

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)

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.

The "clsDataLayer" does not exists in current context

I have been trying to figure this out for hours now, I know there is some small error that I have here but I am not able to pinpoint it. Please help me.
So I created a class called "clsDataLayer.cs" and it is in the App_Code asp.net folder.
I then created a form called "frmUserActivity", but now when I post the code in it and call the class it says "The "clsDataLayer" does not exists in current context" Can anyone please help me?
code for clsDataLayer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// Add your comments here
using System.Data.OleDb;
using System.Net;
using System.Data;
namespace ASP_PayRoll.App_Code
{
public class clsDataLayer
{
// This function gets the user activity from the tblUserActivity
public static dsUserActivity GetUserActivity(string Database)
{
// Add your comments here
dsUserActivity DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Add your comments here
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
// Add your comments here
sqlDA = new OleDbDataAdapter("select * from tblUserActivity", sqlConn);
// Add your comments here
DS = new dsUserActivity();
// Add your comments here
sqlDA.Fill(DS.tblUserActivity);
// Add your comments here
return DS;
}
// This function saves the user activity
public static void SaveUserActivity(string Database, string FormAccessed)
{
// Add your comments here
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblUserActivity (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
// This function gets the IP Address
public static string GetIP4Address()
{
string IP4Address = string.Empty;
foreach (IPAddress IPA in
Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != string.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
}
}
Code for frmUserActivity.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASP_PayRoll
{
public partial class frmUserActivity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Declare the DataSet
dsUserActivity myDataSet = new dsUserActivity();
//Fill the dataset with what is returned from the function
myDataSet = clsDataLayer.GetUserActivity(Server.MapPath("PayrollSystem_DB.mdb"));
//Sets the DataGrip to the DataSource based on the table
grdUserActivity.DataSource = myDataSet.Tables["tblUserActivity"];
//Binds the DataGrid
grdUserActivity.DataBind();
}
}
}
}
Thanks in advance.
Ak
Use ASP_PayRoll.App_Code.clsDataLayer. Your namespace in your data layer class is ASP_PayRoll.App_Code and in your page it's ASP_PayRoll.
Add using ASP_PayRoll.App_Code; to your aspx file.
Since you declared that in a namespace other than the one of your aspx page, you have to use a using statement, or the entire path (ASP_PayRoll.App_Code.clsDataLayer) in order to be able to access that class.

Arithmetic operation resulted in an overflow error c#

Hello i'm using c# to build an application to connect to remote mysql server.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace login
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (tryLogin(textBox1.Text, textBox2.Text) == true)
{
MessageBox.Show("Authed!");
}
else
{
MessageBox.Show("Auth Failure.");
}
}
public bool tryLogin(string username, string password)
{
MySqlConnection con = new MySqlConnection("host=myhostname;user=myusername;password=mypassword;database=mydatabase;");
MySqlCommand cmd = new MySqlCommand("SELECT * FROM test WHERE username = '" + username + "' AND password = '" + password + "';");
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() != false)
{
if (reader.IsDBNull(0) == true)
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return false;
}
else
{
cmd.Connection.Close();
reader.Dispose();
cmd.Dispose();
return true;
}
}
else
{
return false;
}
}
}
}
It shows the following error:
"OverflowException was unhandled
Arithmetic operation resulted in an overflow "
I'm not using any arithmetic operations here. Any help ???
Check the test table in mysql server.
Make sure that all fields have valid values in the username and password columns.
UPDATE
try to include the option "Use Pipe=false;",with your connection string.Then it will opens the connection just fine.
I hope this will help to you.

Categories

Resources