Click here to Skip to main content
15,902,198 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
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
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;
        }
    }
Posted
Updated 21-Aug-18 18:53pm

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
 
Share this answer
 
Comments
Muhammad nur Ihsan 22-Aug-18 0:58am    
can you tell me how? to make my program work for my 2nd device do i need to install the server (sqlexpress) manually?
MadMyche 22-Aug-18 9:14am    
"How" depends on the method that you choose; so are you going to run a shared database or are you going to deploy the database onto the client?
Muhammad nur Ihsan 22-Aug-18 21:33pm    
im wanted to deploy the database onto client i think.. , another problem of mine every i add prereqissites and choose to download from the same location as my application, i cant install the application and why there is no Windows Installer option in my prerequistes
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



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();
            }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900