ASP.net Identity Webservice Authentication - asp.net

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.

Related

The name 'General' does not exist in the current context. in ASP.Net

I've searched and tried a lot to solve this small problem. the ASP.NET problem is
"The name 'General' does not exist in the current context."
[General] is a class which contains two functions.
Please how to solve it.
I am beginner in programming
this is the class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
namespace B5CS
{
public class General
{
public static SqlConnection GetConnection()
{
string strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["strConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnection);
return con;
}
public static DataTable GetDataTable(string sql,SqlConnection con)
{
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}}
here is where I want to use the class "General", in a master page
private void LoadLeftMenu()
{
SqlConnection con = General.GetConnetion();
string sql = "select fld_MenuID,fld_MenuName from tbl_Menus order by fld_MenuName";
DataTable dt = General.GetDataTable(sql, con);
this.DataList1.DataSource = dt;
this.DataList1.DataBind();}}
General class is public so should be accessible anywhere in the code. However class/namespace containing the method LoadLeftMenu() is unable to access the General class.
Please check if LoadLeftMenu() method containing namespace == B5CS, else include it to the top of your LoadLeftmenu() class code i.e. "using [Namespace]" according to your project code.
Also trying checking if your classes are private and hence not accessible. For testing purposes, change them to protected or public and latter change back to suit your project needs.

how to trim the white spaces in the output of json webservice asp.net

Hi (I'm new to JSON this is my 1st webservice)
I have created an Webservice in asp.net that returns JSON data.Every thing works fine but what i need is when fetching the data from the database it should trim the white spaces before it displays.
Because in my data base i have given the field type as nvarchar(100) but inserted the text with <20 characters so in the output i'm getting the result with whitespaces also
For eg:
{"Cargo":[{"Id":1,"FirstName":"devi ","LastName":"priya ","Contactno":"965577796 "}]}
after the name devi and priya there is lots if spaces.
But the actual result i supposed to get is;
{"Cargo":[{"Id":1,"FirstName":"devi","LastName":"priya ","Contactno":"965577796 "}]}
Here is my code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace Webservice
{
/// <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
{
public Service1()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
//public string GetEmployees(string SearchTerm)
public void GetEmployees()
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Contact e ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col]);
}
rows.Add(row);
}
//return serializer.Serialize(rows);
//return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
//JavaScriptSerializer js = new JavaScriptSerializer();
//string strJSON = js.Serialize(new { Cargo = rows });
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
//return serializer.Serialize(new { Cargo = rows });
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
}
can any one please help me.
thanks in advance.
hi the following code helps me to trim the white spaces:
row.Add(col.ColumnName, rs[col].ToString().Trim());

how to ignore default value(string) in the output of Json webservice

I need to neglect the default value(*string *) in the output which is displayed when executing the webservice JSON.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace Webservice
{
[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
{
public Service1()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
//public string GetEmployees(string SearchTerm)
public string GetEmployees()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Contact e ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col]);
}
rows.Add(row);
}
return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}
}
Output is;
<string>
{ "Cargo": [{"Id":1,"FirstName":"devi","LastName":"priya ","Contactno":"965577796 "},{"Id":2,"FirstName":"arun","LastName":"kumar","Contactno":"9944142109"},{"Id":3,"FirstName":"karu","LastName":"ronald","Contactno":"8883205008"}]}
</string>
But the actual output i need is;
{ "Cargo": [{"Id":1,"FirstName":"devi","LastName":"priya ","Contactno":"965577796 "},{"Id":2,"FirstName":"arun","LastName":"kumar","Contactno":"9944142109"},{"Id":3,"FirstName":"karu","LastName":"ronald","Contactno":"8883205008"}]}
In the above output i dont want to see the string /string
is there is a way to omit that if so please suggest me.
Thanks in advance
Try replacing return "{ \"Cargo\": " + serializer.Serialize(rows) + "}"; with return serializer.Serialize(new { Cargo = rows });
Your question can be found here:
ResponseFormat.Json returns xml
And try to use this http://www.nuget.org/packages/Newtonsoft.Json/
it can be very helpful to deal with JSON.
Good Luck.

Name does not exist in current context

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;
}
}
}

SQLCommand (type or name could not found. are you missing any directives )?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
namespace WcfService1
{
/// <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
{
string Connection = "server=SHUMAILA-PC; database=kse; Connect Timeout=10000";
[WebMethod]
public void SQLconn()
{
SqlConnection DataConnection = new SqlConnection(Connection);
// the string with T-SQL statement, pay attention: no semicolon at the end of //the statement
string Command = "INSERT INTO login VALUES (shumaila,mypassword)";
// create the SQLCommand instance
SQLCommand DataCommand = new SqlCommand(Command, DataConnection);
// open the connection with our database
DataCommand.Connection.Open();
// execute the statement and return the number of affected rows
int i = DataCommand.ExecuteNonQuery();
//close the connection
DataCommand.Connection.Close();
}
}
}
I am using system.data.SqlClient directive but still it is giving me this error. what should I do ?
You've got a typo there:
SqlCommand DataCommand = new SqlCommand(Command, DataConnection);
SqlCommand instead of SQLCommand

Resources