How do I setup Linq to SQL and WCF - asp.net

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.

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.

Unable to get data from WCF service using entity framework

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

SqlException when creating a new item in Asp.Net MVC 3 app

In my "web store" mvc app I want to add items to database. Items table has CreatedBy field and it is a foreign key from User table UserId field. Everything was working before I put the database into the App_Data folder. Now I get the SqlException when trying to create a new Item:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Item_contains_User". The conflict occurred in database "C:\USERS\ALEKSEY\REPOS\2\WEBSTORE\WEBSTORE\APP_DATA\WEBSTORE.MDF", table "dbo.Users", column 'UserId'.
Here is the Create method of ItemRepository class:
public Item CreateItem(int productId, Guid userId)
{
var item = new Item
{
ProductId = productId,
CreatedBy = userId,
};
_dataContext.Items.InsertOnSubmit(item);
_dataContext.SubmitChanges(); // in this line the exception occures !
return item;
}
Here is the controller method Create:
[HttpGet]
public ViewResult Create()
{
var p = _productRepository.CreateProduct("", "", 0, "", "", "");
var userId = (Guid)Membership.GetUser().ProviderUserKey;
var item = _itemsRepository.CreateItem(p.ProductId, userId);
// some code
return View(model);
}
Besides, I use Linq to Sql model drag an' drop approach.
Here is the changed web.config connection string part:
<connectionStrings>
<add name="WebStoreConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\WebStore.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
As I said everything was working before I moved the database to App_Data file. I also tried to remove the dependency between Items and Users tables - the exact same exception.
Any help would be appropriate. Thanks in advance!
Edits:
Ok, now I really broke the dependency between Items and Users tables and no exception occures. But! I have to somehow know who has created each product, so breaking the dependency is not an option. I also tried to remove all code that initializes the CreatedBy field.
Any ideas??
Edits (part 2):
The second comment below gives a great advise! I found that all users that are created are stored now in the aspnet.sdf database!!!
But if I remove the connection string "DeafaultConnection":
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
I will get ConfigurationErrorsException:
"The connection name 'DefaultConnection' was not found in the applications
configuration or the connection string is empty."
in the folowing line:
var userId = (Guid)Membership.GetUser().ProviderUserKey;
Ok, as I guessed the issue was in the configuration. Each provider (for some reason) in the connection string had "DefaultConnection". I changed it to "WebStoreConnectionString". And now everything works!
p.s. thanks #w0lf, he pushed the thoughts in the right direction)

Dynamic Connection String

Good Day,
I have two connection strings defined in my web.config file.
<connectionStrings>
<add name="AppDb" connectionString="CONNECTION-STRING1"/>
<add name="LaptopDb" connectionString="CONNECTION-STRING2" />
</connectionStrings>
When I am working on my desktop, I want to use the connection string "AppDb". When I am working on my laptop, I want to use the connection string "LaptopDb". I don't want to comment out the line on the connection string everytime I work on a different machine.
I know that I can programatically do this. I'm just trying to figure out the best way.
Something like:
if (machineName == desktop)
use AppDb
else
use LaptopDb
but I don't like this approach. Is there something else I can test on?
Here's another couple of approaches you could consider:
You can use the configSource attribute to read the configuration for that element from another file, the contents of which can be different on each machine:
http://weblogs.asp.net/fmarguerie/archive/2007/04/26/using-configsource-to-split-configuration-files.aspx
Or you can use different build configurations and use XDT to transform the web.config file.
Really not too hard to do -- the trick is to use the System.Environment.MachineName to drive which string to pick and to get your connection string from a static property:
public static string ConnectionStringName
{
get
{
var customConnection = ConfigurationManager.ConnectionStrings[Environment.MachineName] != null;
var connectionStringName = customConnection ? Environment.MachineName : "DefaultDb";
return connectionStringName;
}
}

'System.Configuration.ConfigurationManager.AppSettings' is a 'property' but is used like a 'method'

Configuration File
<add key="ObjConn" value="Provider=SQLOLEDB;Persist Security Info=True;User
ID=OMembers;PWD=OMembers;Initial Catalog=Omnex2007;Data Source=192.168.100.131"/>
C# Code
strconnection = System.Configuration.ConfigurationManager.AppSettings("ObjConn");
sqlcon = new SqlConnection(strconnection);
you need to use
ConfigurationManager.AppSettings["ObjConn"]
instead of
ConfigurationManager.AppSettings("ObjConn")
Preferred approach is use below settings in config file
<connectionStrings>
<add name="ObjConn" connectionString="your connection string" providerName="System.Data.SqlClient"/>
</connectionStrings>
and use ConfigurationManager.ConnectionStrings["ObjConn"] in your code to retrieve it
try
strconnection = System.Configuration.ConfigurationManager.AppSettings["ObjConn"];
sqlcon = new SqlConnection(strconnection);
This is one of the language syntax differences between C# and VB. Array accessors in VB use parentheses () while in c# they use square brackets [].
In VB, Something(1) could be calling a function named "Something" and passing a 1 as a parameter, OR it could be that Something is an array or a list, and you're accessing the item at index 1.
in C#, Something(1) is ALWAYS a call to a function named Something, while Something[1] would indicate that Something is an Array or a List, and you're accessing an item in a list.
In C# you should use like
strconnection = System.Configuration.ConfigurationManager.AppSettings["ObjConn"];
change and try again.
Generally, the accessing of Config entry values which you have tried in your coding will be used in VB.net coding, but in C# you should use [] with a key name(string format) inside the square brackets, to get the Config entry values.

Resources