如何创建C#visualstud设置包括其他设备的服务器 [英] How do I create C# visualstud setup include the server for other device

查看:95
本文介绍了如何创建C#visualstud设置包括其他设备的服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先抱歉我的英语和新的我需要帮助..

我使用Visual Studio 2017,C#,Microsoft SQL管理工作室



myproblem:

我已经创建了一个安装文件,并在不同的设备上试用了这个程序

这发生了



它在我的电脑中正常工作,我用




$ b $创建项目bi在我的笔记本电脑中安装程序我按下登录/注册按钮它会弹出错误窗口



-

未处理的异常有发生在您的申请中。如果单击继续,应用程序将立即关闭。



建立与SQL Server的连接时发生与网络相关或特定于实例的错误。 找不到服务器或无法访问服务器。验证实例名称是否正确错误:26 - 错误定位服务器/实例指定。


-

是主输出和idf& mdf文件和一些dll ..

所以如何准确创建c#visualstudio设置包括sql server?

直到启动其他设备登录按钮正常工作..谢谢



我尝试了什么:



Form1

登录按钮

first of all sorry with my english and new i rly need help..
what i used Visual Studio 2017 , C# , Microsoft SQL Management Studio

myproblem:
i've created a setup files and tried the program in different device
and this happend

it works normally in my pc where i create the project with

and when
i installed the program in my laptop i press the login/register button it pop up error window

-
Unhandled exception has occurred in your application. if you click Continue, the application will close immediately.

A network-related or instance-specific error occured while establish a connection to SQL server. The server was not found or was not accessible.Verify that the instance name is correct error: 26 - error locating server/instance specified.

-

in my setup project are primary output and idf&mdf files and some dlls..
so how to exactly create c#visualstudio setup include the sql server?
until launching in other device login button's working.. thanks

What I have tried:

Form1
login button

private void btnLogin_Click(object sender, EventArgs e)
       {
           List<SqlParameter> sqlParams = new List<SqlParameter>();
           sqlParams.Add(new SqlParameter("Username", TxtUsername.Text));
           sqlParams.Add(new SqlParameter("Password", txtPassword.Text));

           DataTable dtLoginResults = DAL.ExecSP("ValidateLogin", sqlParams);

           if (dtLoginResults.Rows.Count == 1)
           {
               //We know login is valid
               string user = dtLoginResults.Rows[0]["Username"].ToString();
               MessageBox.Show(user + " Berhasil Masuk!");
               this.Hide();
               ListMeja lm = new ListMeja();
               lm.ShowDialog();
           }
           else
           {
               //invalid login
               MessageBox.Show("Password Salah");
           }
       }





Form2

注册按钮



Form2
Register Button

private void button1_Click(object sender, EventArgs e)
        {
            List<SqlParameter> sqlParams = new List<SqlParameter>();
            sqlParams.Add(new SqlParameter("Username", txtusername.Text));
            sqlParams.Add(new SqlParameter("Password", txtpassword.Text));

            DAL.ExecSP("CreateUser", sqlParams);

            MessageBox.Show("User Berhasil Dibuat!"); 
        }





DAL.cs



DAL.cs

public static class DAL
    {
        public static DataTable ExecSP(string spName, List<SqlParameter> sqlParams = null)
        {
            string strConnect = "Server=PC\\SQLEXPRESS;Database=MyLoginApp;Trusted_Connection=True;";     
            SqlConnection conn = new SqlConnection();
            DataTable dt = new DataTable();

            try
            {
                //Connect to the database
                conn = new SqlConnection(strConnect);
                conn.Open();

                //Build an sql command / query
                SqlCommand cmd = new SqlCommand(spName, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddRange(sqlParams.ToArray());

                //Execute command
                SqlCommand command = conn.CreateCommand();
                SqlDataReader dr = cmd.ExecuteReader();

                //fill datatable with the results
                dt.Load(dr);


            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //No matter what happends this will run
                conn.Close();
            }
            return dt;
        }
    }

推荐答案

您需要在部署的计算机上创建SQL Express实例至;或者您可以更改连接字符串以连接到网络可访问的实例
You would need to create that instance of SQL Express on the machines this is deployed to; or you could change the connection string to connect to a network accessible instance


i need still to have the sql server(sqlexpress) turned on or the db wont work 
Error: 26 - Error Locating Server/Instance Specified

what i've did so far 
i did deploy the database and here's the
script.sql i also put the .sql in Setup Project also the .idf&.mdf files
<pre>
USE [master]
GO
/****** Object:  Database [MyLoginApp]    Script Date: 8/22/2018 11:01:57 AM ******/
CREATE DATABASE [MyLoginApp]
 CONTAINMENT = NONE
 ON  PRIMARY 
( NAME = N'MyLoginApp', FILENAME = N'E:\TOOL\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\MyLoginApp.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'MyLoginApp_log', FILENAME = N'E:\TOOL\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\MyLoginApp_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [MyLoginApp] SET COMPATIBILITY_LEVEL = 100
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [MyLoginApp].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [MyLoginApp] SET ANSI_NULL_DEFAULT OFF 
GO
ALTER DATABASE [MyLoginApp] SET ANSI_NULLS OFF 
GO
ALTER DATABASE [MyLoginApp] SET ANSI_PADDING OFF 
GO
ALTER DATABASE [MyLoginApp] SET ANSI_WARNINGS OFF 
GO
ALTER DATABASE [MyLoginApp] SET ARITHABORT OFF 
GO
ALTER DATABASE [MyLoginApp] SET AUTO_CLOSE ON 
GO
ALTER DATABASE [MyLoginApp] SET AUTO_SHRINK OFF 
GO
ALTER DATABASE [MyLoginApp] SET AUTO_UPDATE_STATISTICS ON 
GO
ALTER DATABASE [MyLoginApp] SET CURSOR_CLOSE_ON_COMMIT OFF 
GO
ALTER DATABASE [MyLoginApp] SET CURSOR_DEFAULT  GLOBAL 
GO
ALTER DATABASE [MyLoginApp] SET CONCAT_NULL_YIELDS_NULL OFF 
GO
ALTER DATABASE [MyLoginApp] SET NUMERIC_ROUNDABORT OFF 
GO
ALTER DATABASE [MyLoginApp] SET QUOTED_IDENTIFIER OFF 
GO
ALTER DATABASE [MyLoginApp] SET RECURSIVE_TRIGGERS OFF 
GO
ALTER DATABASE [MyLoginApp] SET  DISABLE_BROKER 
GO
ALTER DATABASE [MyLoginApp] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
GO
ALTER DATABASE [MyLoginApp] SET DATE_CORRELATION_OPTIMIZATION OFF 
GO
ALTER DATABASE [MyLoginApp] SET TRUSTWORTHY OFF 
GO
ALTER DATABASE [MyLoginApp] SET ALLOW_SNAPSHOT_ISOLATION OFF 
GO
ALTER DATABASE [MyLoginApp] SET PARAMETERIZATION SIMPLE 
GO
ALTER DATABASE [MyLoginApp] SET READ_COMMITTED_SNAPSHOT OFF 
GO
ALTER DATABASE [MyLoginApp] SET HONOR_BROKER_PRIORITY OFF 
GO
ALTER DATABASE [MyLoginApp] SET RECOVERY FULL 
GO
ALTER DATABASE [MyLoginApp] SET  MULTI_USER 
GO
ALTER DATABASE [MyLoginApp] SET PAGE_VERIFY CHECKSUM  
GO
ALTER DATABASE [MyLoginApp] SET DB_CHAINING OFF 
GO
ALTER DATABASE [MyLoginApp] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) 
GO
ALTER DATABASE [MyLoginApp] SET TARGET_RECOVERY_TIME = 0 SECONDS 
GO
ALTER DATABASE [MyLoginApp] SET DELAYED_DURABILITY = DISABLED 
GO
USE [MyLoginApp]
GO
/****** Object:  Table [dbo].[Users]    Script Date: 8/22/2018 11:01:57 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Username] [nvarchar](32) NOT NULL,
	[Password] [nvarchar](64) NOT NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  StoredProcedure [dbo].[CreateUser]    Script Date: 8/22/2018 11:01:57 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Ihsan
-- Create date: 
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[CreateUser] 
	-- Add the parameters for the stored procedure here
	@Username nvarchar(32),
	@Password nvarchar(64)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	INSERT INTO Users (Username, Password) VALUES (@Username, @Password);
END
GO
/****** Object:  StoredProcedure [dbo].[ValidateLogin]    Script Date: 8/22/2018 11:01:57 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Ihsan
-- Create date: 
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[ValidateLogin] 
	-- Add the parameters for the stored procedure here
	@Username nvarchar(32),
	@Password nvarchar(64)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * FROM Users WHERE Username = @Username AND Password = @Password;
END
GO
USE [master]
GO
ALTER DATABASE [MyLoginApp] SET  READ_WRITE 
GO







在我的登录表单中我添加了

来检查数据库是否存在或者不是它

返回bool值如果不是






and in my login form i've added this
to check whether database exist or not it
return bool value if not

private bool CheckDatabaseExist()
        {
            //Sql Connection for User Defined Database
            SqlConnection Connection = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Collage;Integrated Security=True");
            try
            {
                Connection.Open();
                return true;
            }
            catch
            {
                return false;
            }
        }

        private void GenerateDatabase()
        {
            List<string> cmds = new List<string>();
            //reading our script file from the installed application folder
            if (File.Exists(Application.StartupPath + "\\script.sql"))
            {
                TextReader tr = new StreamReader(Application.StartupPath + "\\script.sql");
                string line = "";
                string cmd = "";
                while ((line = tr.ReadLine()) != null)
                {
                    if (line.Trim().ToUpper() == "GO")
                    {
                        cmds.Add(cmd);
                        cmd = "";
                    }
                    else
                    {
                        cmd += line + "\r \n";
                    }
                }
                if (cmd.Length > 0)
                {
                    cmds.Add(cmd);
                    cmd = "";
                }
                tr.Close();
            }
            if (cmds.Count > 0)
            {
                SqlCommand command = new SqlCommand();
                //SqlConnection for master database
                //This sql connection for master database it is used to generate database 
                command.Connection = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=MASTER;Integrated Security=True");
                command.CommandType = System.Data.CommandType.Text;
                command.Connection.Open();
                for (int i = 0; i < cmds.Count; i++)
                {
                    command.CommandText = cmds[i];
                    command.ExecuteNonQuery();
                }
            }
        }

        private void Login_Load(object sender, EventArgs e)
        {
            //Checking whether database exist or not it returns bool value if not then it generate the database
            if (!CheckDatabaseExist())
            {
                GenerateDatabase();
            }
}


这篇关于如何创建C#visualstud设置包括其他设备的服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆