Name does not exist in current context - asp.net

I am trying to update a view using a gridview with edit and update buttons. I am using some code from code projects and the code looks like this :
private void BindData()
{
string strQuery = "SELECT * FROM [vw_GridviewSource] WHERE (([Annotation Date] = #Annotation_Date) AND ([Name] = #Name))";
SqlCommand cmd = new SqlCommand(strQuery);
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
I am getting an error that the name 'GetData' does not exist in the current context.
My using statements are:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
Do I need to add another statement?

It looks like you missed implementing the GetData function. After some quick Googling I found this which looks like it might suit your needs.
private DataTable GetData(SqlCommand cmd)
{
//string connectionString;
connectionString = "";
connectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=TEST_DB;Data Source=DELL-PC";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
}
}

Related

Retrieve name and image from database where image is stored as upload folder and reference is stored in database?

Trying the following code but could't get the desired result.
I have stored the image in the upload folder and its reference is saved in database while storing the data in the database from the admin side.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace Admin
{
public partial class fetch : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs =
ConfigurationManager.ConnectionStrings["DBSC"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spUploadImage", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter ParamId = new SqlParameter()
{
ParameterName = "#Id",
Value = Request.QueryString["Id"]
};
cmd.Parameters.Add(ParamId);
con.Open();
byte[] Bytes = (byte[])cmd.ExecuteScalar();
string strBase64 = Convert.ToBase64String(bytes);
FileUpload1.ImageUrl = "data:image/png;base64, +strBase64";
}
}
}
}

SQLException Occured

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
I was trying database connection. But I am getting this error. Please help me.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace OLSWebApp
{
public partial class ItemTypeWebForm : System.Web.UI.Page
{
static string constr = "server=DESKTOP-3N4UH9N; user=sa; pwd=ZEESHAN#123; Initial Catalog=Online Order System";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SaveButton_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(constr);
conn.Open();
string q = "Insert INTO ItemType values ('"+ TypeIdTextBox.Text +"'), ('"+ TypeTextBox.Text +"'),('"+ NameTextBox.Text +"')";
SqlCommand cmd = new SqlCommand(q,conn);
cmd.ExecuteNonQuery();
}
}
}
con.Open() statement generates error..
For SQL Server Connection types please first read this document.
https://www.connectionstrings.com/sql-server/
For your example I think DESKTOP-3N4UH9N is your local PC not the server instance name, isn't it?
Please first find the server instance name by using SQL Server Management Studio (SSMS).
Please try below codes
Standard Security
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Server=myServerAddress; " +
"Database=myDataBase;" +
"User Id=myUsername;" +
"Password=myPassword;"
conn.Open();
Trusted Connection
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Server=myServerAddress;" +
"Database=myDataBase;" +
"Trusted_Connection=True;"
conn.Open();
Connection to a SQL Server instance
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Server=myServerName\myInstanceName;" +
"Database=myDataBase;" +
"User Id=myUsername;" +
"Password=myPassword;"
conn.Open();
Integrated Security
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=MyLocalSqlServerInstance;" +
"Initial Catalog=MyDatabase;" +
"Integrated Security=SSPI;"
conn.Open();
change this
conn.Open();
string q = "Insert INTO ItemType values ('"+ TypeIdTextBox.Text +"'), ('"+ TypeTextBox.Text +"'),('"+ NameTextBox.Text +"')";
SqlCommand cmd = new SqlCommand(q,conn);
cmd.ExecuteNonQuery();
into this
conn.Open();
string q = "Insert INTO ItemType values (#id, #type ,#name)";
SqlCommand cmd = new SqlCommand(q,conn);
cmd.Parameters.AddWithValue("#id", TypeIdTextBox.Text);
cmd.Parameters.AddWithValue("#type", TypeTextBox.Text);
cmd.Parameters.AddWithValue("#name", NameTextBox.Text);
cmd.ExecuteNonQuery();
conn.Close();
make sure the connection can open without any error

ASP.net Identity Webservice Authentication

I've a simple ASP.net Webforms application with authentication using Identity+Owin. Based on this tutorial here:
https://learn.microsoft.com/en-us/aspnet/identity/overview/getting-started/adding-aspnet-identity-to-an-empty-or-existing-web-forms-project
I've also added a webservice as code given bellow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Newtonsoft.Json;
namespace webservice_1
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.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 WebService1 : System.Web.Services.WebService
{
[WebMethod]
public DataSet getRequests()
{
DataSet ds = new DataSet();
string cs = ConfigurationManager.ConnectionStrings["IBS_5"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand sqlComm = new SqlCommand("spSelRequests", con);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
return ds;
}
}
[WebMethod]
public string getRqsts()
{
DataSet ds = new DataSet();
string cs = ConfigurationManager.ConnectionStrings["IBS_5"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand sqlComm = new SqlCommand("spSelRequests", con);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
return JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);
}
}
}
}
Everything is working fine. I just want to add authentication to the webservice. Currently webservice can be called directly and no security is there.
Authentication is working fine for web pages.
The webservices will be used for android/IOS applications.
I m clueless how should I provide authentication here. Also how should I manage cookies and sessions for webservice.
Note: MVC is not understood by me...so pls consider.

SQL Server is not showing any output

I am using this code to verify user but it always displays 'User not found'. Whether I use complete select command with where clause or not. Answer is same every time. Although it shows some result in general but I can't match one result.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Configuration;
public partial class Applicant : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(myConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cn.Open();
SqlDataReader conReader = null;
cmd.CommandText = "Select * from Applicant ";
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
// cmd.Parameters.AddWithValue("#userName", myid);
// cmd.Parameters.AddWithValue("#UserPassword", mypass);
try
{
conReader = cmd.ExecuteReader();
bool _userfound = false;
while (conReader.Read())
{
if (conReader[0].ToString() == myid.ToString() && conReader[1].ToString() == mypass.ToString())
{
_userfound = true;
break;
}
}
if (_userfound)
Response.Write("User Found");
else
Response.Write("User not Found");
}
catch (Exception ex)
{
Console.Write(ex);
}
finally
{
cn.Close();
}
}
}
}
}
You should make the query complete, e.g.:
cmd.CommandText = "Select * from Applicant where UserName = #userName";
Only then will adding a parameter (of the same name) be substituted in the query.

Not all paths return a value error in Model class

My model class looks like this:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace OEWebPortalMVCVer5.Models
{
class DenialModel
{
public Dictionary< string, DataSet> DataSets { get; set; }
public static DataSet ReadRows(DataSet dataset)
{
try
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["demo10ConnectionString"].ConnectionString);
string startDate = "1/1/1900";
string endDate = "12/31/2020";
conn.Open();
DataSet dtDS = new DataSet();
SqlCommand dtCom = new SqlCommand("dbo.cusGenDenialReport", conn);
dtCom.Parameters.AddWithValue("#StartDate", SqlDbType.DateTime).Value = Convert.ToDateTime(startDate);
dtCom.Parameters.AddWithValue("#EndDate", SqlDbType.DateTime).Value = Convert.ToDateTime(endDate);
dtCom.CommandType = CommandType.StoredProcedure;
SqlDataAdapter dtDa = new SqlDataAdapter(dtCom);
dtDa.Fill(dtDS);
conn.Close();
dtCom.Dispose();
}
catch (Exception ex)
{
string message = "It didn't work because: " + ex.Message.ToString();
}
}
}
}
When I attempt to build the solution in VS2012 it throws the following error:
Error 1 'OEWebPortalMVCVer5.Models.DenialModel.ReadRows(System.Data.DataSet)': not all code paths return a value C:\Users\Orchestrate\documents\visual studio 2012\Project\OEWebPortalMVCVer5\OEWebPortalMVCVer5\Models\DenialModel.cs 22 31 OEWebPortalMVCVer5
My first thought was that I did not handle the null value for the parameter startDate and endDate so I hard coded them and will address that later. That was not the case so I added a try catch block to get the error. Well that of course didn't help (I must have gotten very tired to think that the try catch would magically fix it). I have googled this error and searched this site and haven't found any related answers to this problem.
I am not sure how to get the code to compile properly at this point. Any help is appreciated
Thank you
The error says exactly what's the problem : there's no return statement in your function.
public static DataSet ReadRows(DataSet dataset)
{
DataSet dtDS = null;
try
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["demo10ConnectionString"].ConnectionString);
string startDate = "1/1/1900";
string endDate = "12/31/2020";
conn.Open();
dtDS = new DataSet();
SqlCommand dtCom = new SqlCommand("dbo.cusGenDenialReport", conn);
dtCom.Parameters.AddWithValue("#StartDate", SqlDbType.DateTime).Value = Convert.ToDateTime(startDate);
dtCom.Parameters.AddWithValue("#EndDate", SqlDbType.DateTime).Value = Convert.ToDateTime(endDate);
dtCom.CommandType = CommandType.StoredProcedure;
SqlDataAdapter dtDa = new SqlDataAdapter(dtCom);
dtDa.Fill(dtDS);
conn.Close();
dtCom.Dispose();
}
catch (Exception ex)
{
//You probably should let it break...
string message = "It didn't work because: " + ex.Message.ToString();
}
return dtDS;
}

Resources