Unable to get data from WCF service using entity framework - asp.net

I am using a web application where user pass one argument to the service and it will return string datatype which is query result. In the service i am using Entity Framework to query based on the user input but i am unable to get the data instead throwing an exception in my webapplication saying.....
The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
Webapplication and service are two different solutions.
Code in My WCF service
public string GetFunctionality(string UserId)
{
string strRoleName = string.Empty;
objEntity = new SYMPHONY_TVEntities();
var Function = from t1 in objEntity.Users join t2 in objEntity.User_Role on t1.Role equals t2.User_Role1 where t1.UserID == UserId select t2;
var UserName = from it in objEntity.Users where it.UserID == UserId select it;
//Here i am getting exception
User_Role objRole = Function.First();
User objUser = UserName.First();
if (objRole.User_Function != null && objUser.User_Name != null)
{
strRoleName = objRole.User_Function + "$" + objUser.User_Name;
}
return strRoleName;
}
My connection string WCF service
<add name="SYMPHONY_TVEntities" connectionString="metadata=res://*/UsersModel.csdl|res://*/UsersModel.ssdl|res://*/UsersModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=inhi1u-hd0212\;Initial Catalog="SYMPHONY TV";Integrated Security=True;MultipleActiveResultSets=True'" providerName="System.Data.EntityClient" /></connectionStrings>

You code looks ok. The exception says it is unable to connect to the db. This means your connection string might be wrong, please verify your connection string. If this fails try adding this line of code after your objEntity. (Why?)
objEntity = new SYMPHONY_TVEntities();
objEntity.Connection.Open();

Related

Login authentication to asp.net and postgresql

I have tried to implement login page in ASP.NET Core MVC and using postgresql as database.
It should check whether user exits in the database table of postgresql and verify, so what is the query to search for user in database and made them sign in?
I have written my code like this:
public IActionResult Login(string seller_email, string seller_password)
{
using var connection = new NpgsqlConnection(connString);
connection.Open();
string main_query = String.Format(#"select exists(select 1 from public.""sellers"" where ""seller_email""='{0}')", seller_email);
using var command_main = new NpgsqlCommand(main_query, connection);
int result_main = command_main.ExecuteNonQuery();
if (result_main < 0)
{
return View(nameof(Create));
}
else
{
return View(nameof(Sign));
}
}
There is a seller table in the database, so just have to check seller exists or not - if exists the have to create a view for it
You are doing a select query, so you must use a command.ExecuteReader.
The ExecuteNonQuery is to be used with statements that update/insert/delete records.
BUT, most importantly, don't concatenate user submitted values into the query string, as it opens the door to SQL injections. Instead, used a parameter.
See the getting started doc for a simple example.

CAS SSO for Asp.Net website, attributes not receiving on serviceValidate request

I have successfully integrated CAS for our different clients. But this time 'samlValidate' response is not consistently supplying the required attribute. Login is failing randomly because of the missing attribute in the ticket validation response. Sometimes when I clear browser history, it's receiving the attribute in the response.
Expected response:
<cas:serviceResponse xmlns:cas='http://www.xxxxx.xxx/tp/cas'>
<cas:authenticationSuccess>
<cas:user>xxxxx</cas:user>
<cas:attributes>
<cas:userNumber>1234567</cas:userNumber>
</cas:attributes>
</cas:authenticationSuccess>
</cas:serviceResponse>
Response receiving randomly:
<cas:serviceResponse xmlns:cas='http://www.xxx.xxx/tp/cas'>
<cas:authenticationSuccess>
<cas:user>xxxxxx</cas:user>
</cas:authenticationSuccess>
</cas:serviceResponse>
Please note: We have created a custom code to integrate CAS with our Asp.Net webforms application.
string userId = string.Empty;
// Look for the "ticket=" after the "?" in the URL
string tkt = HttpContext.Current.Request.QueryString["ticket"];
// Service url is the url of the Researcher Portal
string service ="www.xyz.com";
string CASHOST="https://cas.xyz.ca:8443/cas"
// First time through there is no ticket=, so redirect to CAS login
if (tkt == null || tkt.Length == 0)
{
string redir = CASHOST + "login?" +
"service=" + service;
HttpContext.Current.Response.Redirect(redir);
}
// Second time (back from CAS) there is a ticket= to validate
string validateurl = CASHOST + "serviceValidate?" +
"ticket=" + tkt +
"&service=" + service;
StreamReader Reader = new StreamReader(new WebClient().OpenRead(validateurl));
string resp = Reader.ReadToEnd();
if (isDebuggingMode)
sbDebugString.Append("****Response **** \n " + resp);
// Some boilerplate to set up the parse.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);
XmlTextReader reader = new XmlTextReader(resp, XmlNodeType.Element, context);
string userNumber = null;
// A very dumb use of XML. Just scan for the "userNumber". If it isn't there, it will return an empty string.
while (reader.Read())
{
if (reader.IsStartElement())
{
string tag = reader.LocalName;
if (isDebuggingMode)
sbDebugString.Append("tag : " + tag + "\n");
if (tag == "userNumber")
{
userNumber = reader.ReadString();
if (isDebuggingMode)
sbDebugString.Append("userNumber : " + userNumber + "\n");
}
}
}
Where "userNumber" attribute is not receiving always so that login fails randomly.
Please share your thoughts to resolve this issue.
Thank you in advance.
If your client application is not receiving attributes, you will need to make sure:
The client is using a version of CAS protocol that is able to
release attributes.
The client, predicated on #1, is hitting the appropriate endpoint for service ticket validation (i.e. /p3/serviceValidate).
The CAS server itself is resolving and retrieving attributes correctly.
The CAS server is authorized to release attributes to that particular client application inside its service registry.
Starting with CAS Protocol 3:
Among all features, the most noticeable update between versions 2.0 and 3.0 is the ability to return the authentication/user attributes through the new /p3/serviceValidate endpoint.
You may also find this post useful:
https://apereo.github.io/2017/06/23/cas-protocol-compatibility/

ASP.NET WCF REST Linq-to-SQL POST/WebInvoke JSON, Object with EntitySet generated by Linq-to-SQL

So my problem is little bit complicated.
Main goal: register account (class / table) that contains list of Players (class / table) from a web application into a SQL Server database through a WCF service.
So for creating the classes I used Linq-to-SQL which created the Account and Player class. The Player has a foreign key AccountEmail to the Account table. Due to that the class Account has EntitySet<Player> _Players;.
Now the web application has reference to this service and when user finish registration I am making an POST request with WebClient and DataContractJsonSerializer to the service .
Unfortunately the service or the http protocol cannot understand the request :
System.Net.WebException: The remote server returned an error: (400)
Full error response from server
https://s31.postimg.org/x6b27uqqj/errorrr.png
The fail is on service side for some reason it doesn't know how to read the json player DB.designer.cs:line 295 at ReadPlayerFromJson(XmlReaderDelegator
Service:
[OperationContract]
[WebInvoke(UriTemplate = "/Register",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, Method = "POST")]
void RegisterAccount(Account account);
Client side :
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Account));
MemoryStream mem = new MemoryStream();
Account a = new Account { EMAIL = Email.Text, PASSWORD = Password.Text, NAME = nickname.Text};
a.Players = accountPLayers.ToArray();
ser.WriteObject(mem, a);
string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadString(WEB_SITE_URL+ "/Register", "POST", data);
When sending Account without the list of players, the operation succeeds:
{"EMAIL":"test#gmail.com","NAME":"1","PASSWORD":"test","Players":null}
With the list of players the operation fails :
{"EMAIL":"test#gmail.com","NAME":"1","PASSWORD":"test","Players":[{"Account":null,"AccountEmail":"test#gmail.com","FirstName":"test","Id":0,"LastName":"test","Type":-1}]}
Questions:
I guess that REST service expecting to get only Account and doesn't know what is the list of players? I have to define that somehow.
Why in the service does the Account have EntitySet<Player> _Players;? And in the client after adding reference to service it is an array Player[] ?
Why does Linq-to-SQL add field Account to player? What should it contain? As you can see this field is null in the json.
Is complex object/known types has to do something with my problem ?
Please help me to solve this issue, thanks!
Solved !!!
So if any one ever will get this problem ,
The thing is that player has foreign key of EMAIL column to Account Email .
When you create your JSON DO NOT PUT EMAIL INSIDE EACH PLAYER
LINQTOSQL knows the association and will add it automatically when parsing the JSON .
So my JSON Sent to the service looks like this :
{"EMAIL":"test#gmail.com","NAME":"test","PASSWORD":"test#A","Players":[{"Account":null,"AccountEmail":null,"FirstName":"wow","Id":0,"LastName":"koko","Type":null}]}.

The underlying provider failed on Open

I made 3 Ajax processes to run the below code at the same time.
but one of the processes throw exception that message says "The underlying provider failed on Open."
try{
orderRepository orderRepo = new orderRepository(); // get context (Mysql)
var result = (from x in orderRepo.orders
where x.orderid == orderno
select new {x.tracking, x.status, x.charged }).SingleOrDefault();
charged = result.charged;
}catch(Exception e){
log.Error(e.Message); // The underlying provider failed on Open.
}
And, I run the 1 Ajax call that failed before, then It passes through.
It happen to 1 of 3 (Ajax) process, sometimes, 2 of 5 process.
I guess it because all process try to using Database same time. but I couldn't find the solution.
This is my connection string,
<add name="EFMysqlContext" connectionString="server=10.0.0.10;User Id=root;pwd=xxxx;Persist Security Info=True;database=shop_db" providerName="Mysql.Data.MySqlClient" />
Anybody know the solution or something I can try, please advise me.
Thanks
It sounds like a problem because of concurrent connection with SQL Server using same username. Have you tried destroying/disposing the repository(or connection) object after using it?
Give it a try:
try{
using( orderRepository orderRepo = new orderRepository()) // get context (Mysql)
{
var result = (from x in orderRepo.orders
where x.orderid == orderno
select new {x.tracking, x.status, x.charged }).SingleOrDefault();
charged = result.charged;
} // orderRepo object automatically gets disposed here
catch(Exception e){
log.Error(e.Message); // The underlying provider failed on Open.
} }
Not sure if it matters, but your provider name is Mysql.Data.MySqlClient and not MySql.Data.MySqlClient (if it is case-sensitive, this could be the cause).

How do I setup Linq to SQL and WCF

So I'm venturing out into the world of Linq and WCF web services and I can't seem to make the magic happen. I have a VERY basic WCF web service going and I can get my old SqlConnection calls to work and return a DataSet. But I can't/don't know how to get the Linq to SQL queries to work. I'm guessing it might be a permissions problem since I need to connect to the SQL Database with a specific set of credentials but I don't know how I can test if that is the issue. I've tried using both of these connection strings and neither seem to give me a different result.
<add name="GeoDataConnectionString" connectionString="Data Source=SQLSERVER;Initial Catalog=GeoData;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="GeoDataConnectionString" connectionString="Data Source=SQLSERVER;Initial Catalog=GeoData;User ID=domain\userName; Password=blahblah; Trusted_Connection=true"
providerName="System.Data.SqlClient" />
Here is the function in my service that does the query and I have the interface add the [OperationContract]
public string GetCity(int cityId)
{
GeoDataContext db = new GeoDataContext();
var city = from c in db.Cities
where c.CITY_ID == 30429
select c.DESCRIPTION;
return city.ToString();
}
The GeoData.dbml only has one simple table in it with a list of city id's and city names. I have also changed the "Serialization Mode" on the DataContext to "Unidirectional" which from what I've read needs to be done for WCF.
When I run the service I get this as the return: SELECT [t0].[DESCRIPTION] FROM [dbo].[Cities] AS [t0] WHERE [t0].[CITY_ID] = #p0
Dang, so as I'm writing this I realize that maybe my query is all messed up?
Try this:
public string GetCity(int cityId)
{
GeoDataContext db = new GeoDataContext();
var city = db.Cities.SingleOrDefault(c => c.CITY_ID == 30429);
return city.DESCRIPTION;
}
The problem with your query is that it's not returning a string in the var, it's returning an IQueryable. So when you ToString() the IQueryable, it must be returning a string representation of the SQL query represented by the IQueryable.

Resources