Metro 应用程序通过 WCF 服务 - 错误连接到 SQL
本文关键字:错误 连接 SQL 服务 应用程序 WCF Metro | 更新日期: 2023-09-27 18:35:17
我为Windows 8创建了一个新的metro应用程序。
我的目的是在地铁应用程序中使用来自 WCF 数据服务的数据。WCF 服务应连接到本地计算机上安装的 SQL 服务器。
我为我的服务设置了一个接口,以便可以将参数传递给我希望 WCF 执行的方法,然后将结果返回到 Metro 应用程序。
我在网上学习了几个不同的教程并取得了成功,直到......
在以下情况下发生与网络相关或特定于实例的错误建立与 SQL Server 的连接。找不到服务器或无法访问。验证实例名称是否正确,以及SQL Server 配置为允许远程连接。(提供者:命名管道提供程序,错误: 40 - 无法打开与 SQL Server 的连接)
我有一个包含来自登录登录页面和SQL配置页面的代码。当 metro 应用程序启动时,它会运行一种方法来检查是否存在连接。如果未找到连接,则会显示 SQL 配置页。
应用程序将启动。On导航到登录表单,CheckConnection() 方法返回 true。但是当我输入用户详细信息并按登录时,我只是在登录页面上的异步 void Login() 方法中的以下代码行中出现错误
newCustomType = await dataServiceClientName.CheckLoginAsync(txtUsername.Text, txtPassword.Text);
如果有人了解为什么此错误显示帮助,将不胜感激。
我在下面包含了相关的代码(或者我可以说是相关的)。
提前致谢:)
代码片段:
精简的服务接口
[ServiceContract]
public interface CTUServiceInterface
{
// TODO: Add your service operations here
//LoginForm
[OperationContract]
bool CheckConnection();
//SQL Config
[OperationContract]
bool UpdateConnectionDetails(string ConnectionString);
//LoginForm
[OperationContract]
LoginDetails CheckLogin(string Username, string Password);
//LoginForm Success
[OperationContract]
UserGlobalDetails GetActiveUserDetails(int UserKey);
}
[DataContract]
public class LoginDetails
{
bool loginSuccess = false;
string errorMessage = "";
int userKey = -1;
[DataMember]
public bool LoginSuccess
{
get { return loginSuccess; }
set { loginSuccess = value; }
}
[DataMember]
public string ErrorMessage
{
get { return errorMessage; }
set { errorMessage = value; }
}
[DataMember]
public int UserKey
{
get { return userKey; }
set { userKey = value; }
}
}
[DataContract]
public class UserGlobalDetails
{
string firstName = "";
string lastName = "";
int departmentKey = -1;
bool manager = false;
[DataMember]
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
[DataMember]
public string LastName
{
get { return lastName; }
set { lastName = value; }
}
[DataMember]
public int DepartmentKey
{
get { return departmentKey; }
set { departmentKey = value; }
}
[DataMember]
public bool Manager
{
get { return manager; }
set { manager = value; }
}
}
精简服务代码
public class CTUService : CTUServiceInterface
{
private static SqlConnection localConnection = new SqlConnection("Data Source=PC-VIRTUAL;Initial Catalog=CarTraUnl;Integrated Security=True");
//LoginForm
public bool CheckConnection()
{
bool result = true;
try
{
localConnection.Open();
localConnection.Close();
}
catch(Exception ex)
{
result = false;
throw ex;
}
return result;
}
//SQL Config
public bool UpdateConnectionDetails(string ConnectionString)
{
localConnection = new SqlConnection(ConnectionString);
return CheckConnection();
}
//LoginForm
public LoginDetails CheckLogin(string Username, string Password)
{
//Initilize the LoginDetails Object to return with results
LoginDetails localDetails = new LoginDetails();
//Initilize the localDataTable to hold sql results
DataTable localDataTable = new DataTable("localDataTable");
//Setup a SqlDataAdapter and get info from the 'UserGlobal' Table
localConnection.Open();
SqlDataAdapter localDataAdapter = new SqlDataAdapter(
"SELECT [Password],[Key]" +
"FROM [CarTraUnl].[dbo].[UserGlobal]" +
"WHERE [Username] = '" + Username + "'"
, localConnection);
localConnection.Close();
//Fill localDataTable with information from the UserGlobal Table
localDataAdapter.Fill(localDataTable);
//Set loginStatus equal to the number of passwords found for the given username
int loginStatus = localDataTable.Rows.Count;
//If no passwords are found, there was no username like the given one
if (loginStatus == 0)
{
localDetails.ErrorMessage = "Invalid Username";
}
//If one password was found, check if it matches the given password
else if (loginStatus == 1 && localDataTable.Rows[0][0].ToString() == Password)
{
localDetails.LoginSuccess = true;
localDetails.ErrorMessage = "";
localDetails.UserKey = int.Parse(localDataTable.Rows[0][1].ToString());
}
//If one password is found, but it doesn't match show the error
else if (loginStatus == 1 && localDataTable.Rows[0][0].ToString() != Password)
{
localDetails.ErrorMessage = "Invalid Password";
}
//If multiple passwords are found, there are duplicate usernames
else if (loginStatus > 1)
{
localDetails.ErrorMessage = "Duplicate Usernames";
}
return localDetails;
}
//LoginForm Success
public UserGlobalDetails GetActiveUserDetails(int UserKey)
{
//Initilize UserGlobalDetails object to return later
UserGlobalDetails localUserGlobalDetails = new UserGlobalDetails();
//Initilize a DataTable to hold our sql results
DataTable localDataTable = new DataTable("localDataTable");
//Setup a SqlDataAdapter and get info from the 'UserGlobal' Table
SqlDataAdapter localDataAdapter = new SqlDataAdapter(
"SELECT [FirstName],[LastName],[DepartmentKey],[Manager]" +
"FROM [CarTraUnl].[dbo].[UserGlobal]" +
"WHERE [Key] = '" + UserKey + "'"
, localConnection);
//Fill localDataTable with information from the 'UserGlobal' Table
localDataAdapter.Fill(localDataTable);
//Configure the UserGlobalDetails object 'localUserGlobalDetails' with the retrived results
localUserGlobalDetails.FirstName = localDataTable.Rows[0][0].ToString();
localUserGlobalDetails.LastName = localDataTable.Rows[0][1].ToString();
localUserGlobalDetails.DepartmentKey = int.Parse(localDataTable.Rows[0][2].ToString());
localUserGlobalDetails.Manager = bool.Parse(localDataTable.Rows[0][3].ToString());
//return the results
return localUserGlobalDetails;
}
}
登录.xaml.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
lblError.Text = "";
}
private async void CheckConnection()
{
CTUServiceReference.CTUServiceInterfaceClient dataServiceClientName = new CTUServiceReference.CTUServiceInterfaceClient();
bool result = await dataServiceClientName.CheckConnectionAsync();
if (result == false)
{
this.Frame.Navigate(typeof(SqlConfig));
}
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
Login();
}
private async void Login()
{
btnLogin.IsEnabled = false;
CTUServiceReference.CTUServiceInterfaceClient dataServiceClientName = new CTUServiceReference.CTUServiceInterfaceClient();
CTUServiceReference.LoginDetails newCustomType = new CTUServiceReference.LoginDetails();
newCustomType = await dataServiceClientName.CheckLoginAsync(txtUsername.Text, txtPassword.Text);
CTUServiceReference.UserGlobalDetails currentActiveUserDetails = new CTUServiceReference.UserGlobalDetails();
currentActiveUserDetails = await dataServiceClientName.GetActiveUserDetailsAsync(newCustomType.UserKey);
//The globalSettings.cs file is not included, but it just holds persistent application data
globalSettings.currentUserKey = newCustomType.UserKey;
globalSettings.firstName = currentActiveUserDetails.FirstName;
globalSettings.lastName = currentActiveUserDetails.LastName;
globalSettings.departmentKey = currentActiveUserDetails.DepartmentKey;
globalSettings.manager = currentActiveUserDetails.Manager;
if (newCustomType.LoginSuccess)
{
//This page is where we go when login is successful
this.Frame.Navigate(typeof(FormSelector));
}
else
{
lblError.Text = newCustomType.ErrorMessage;
btnLogin.IsEnabled = true;
}
}
SQLConfig.xaml.cs
private void btnSqlConfigSave_Click(object sender, RoutedEventArgs e)
{
saveConfig();
}
private async void saveConfig()
{
btnSave.IsEnabled = false;
string connectionstring = "";
if (rbAutomatic.IsChecked == true)
{
//Integrated Secturity
connectionstring = "Data Source=" + txtServer.Text + ";Initial Catalog= " + txtDB.Text + ";Integrated Security=True";
}
else
{
//Standard Authentication with username and password
connectionstring = "Data Source=" + txtServer.Text + ";Initial Catalog= " + txtDB.Text + ";User Id=" + txtUser.Text + ";Password=" + txtPass.Text;
}
CTUServiceReference.CTUServiceInterfaceClient dataServiceClientName = new CTUServiceReference.CTUServiceInterfaceClient();
bool result = await dataServiceClientName.UpdateConnectionDetailsAsync(connectionstring);
if (result)
{
this.Frame.GoBack();
return;
}
else
{
lblError.Text = "Config error";
btnSave.IsEnabled = true;
}
}
版本信息
视觉工作室
- Microsoft Visual Studio Ultimate 2012
- 版本 11.0.50727.1 RTMREL
- Microsoft .NET 框架版本 4.5.50709
- 安装版本:旗舰版
SQL Server
- Microsoft SQL Server Management Studio - 11.0.2100.60
- Microsoft分析服务客户端工具 - 11.0.2100.60
- Microsoft数据访问组件 (MDAC) - 6.2.9200.16384
- Microsoft MSXML - 3.0 6.0
- Microsoft .NET 框架 - 4.0.30319.18051
- 操作系统 - 6.2.9200
此错误可能有多种原因,但它意味着它的含义......存在,您的服务无法访问:
"Data Source=" + txtServer.Text + ";
这很可能不是代码中的问题,而是 SQLServer 配置问题。
我建议您先在 ODBC 调用中尝试 connectionString,看看是否可以从本地和远程访问它。
您的服务似乎尝试通过 SQLServer 配置管理器中的命名管道进行连接,以查看协议是否已为您的特定实例启动。
还要尝试启用 TCP/IP 协议,并检查它是否侦听正确的端口 (1433)。
也可能是您没有针对"命名实例"。 即:
"Data Source=MYSERVER"
而不是
"Data Source=MYSERVER'MyInstance"
希望这有帮助!