Relative positioning Of Database and Images Used in Application

There are situations when we develop an application and it works fine when we running it on the system on which it is made but when we take our application elsewhere it doesn't function properly, usually throwing error like database not found or many times you may not get the picture used in the application.

This happens because the path of your database and picture change when they are moved to different system. Therefore, to avoid such situation we need to make our application relative i.e. we take our application to different system and it works without any errors.

So, in this article we are going to learn how we can make our application relative. I am going to explain the whole scenario by designing a small application.

In order to make our application relative we need to keep number of things in application folder in this example we will be keeping database and image directory in application directory.

So let's begin:

Below is the windows form.

The important thing here is we are accessing data from database which is kept in application directory and same follows for images.

Coding will more or less go the same way as I have discussed in previous articles.

Here goes our table creation:

CREATE TABLE [dbo].[blog_usp_relative](

    [name] [varchar](50) NOT NULL,

    [ph] [numeric](18, 0) NOT NULL,

    [pic] [varchar](max) NOT NULL

)

We would now require stored procedures:

  • For selecting records

CREATE PROCEDURE [dbo].[blog_relative_select]

(

@msg varchar(100) output

)

AS

BEGIN try

    

    SET NOCOUNT ON;

select * from blog_usp_relative;

 

return 0

END try

begin catch

select @msg='Error!!!Problem Occured During Process'

return 1

end catch

 

  • Stored procedure for Inserting records

     

CREATE PROCEDURE [dbo].[blog_relative_insert]

(

 

@name char(50),

@ph numeric(11,0),

@pic varchar(50),

@msg varchar(100) output

)

    -- Add the parameters for the stored procedure here

AS

begin try

begin

BEGIN tran

insert into blog_usp_relative values(@name,@ph,@pic);

commit

select @msg='Insertion Successful'

return 0

end

 

End try

 

BEGIN catch

    SET NOCOUNT ON;

    select @msg='Some Problem Ocured In Processing'

    rollback

    return 1

END catch

C # code:

In c # code we need to remember few important things:

  1. We will have to change our connection string and will have to manipulate it according to the directory where it is kept.
  2. We will have to keep our database in application directory.
  3. Images directory will also have to be kept into application directory.
  4. In this example we are displaying picture against every name so we will have to store image filename in database and not the full location of image.

     

    In my example the application directory name is "blog" and location is "F:\programs\dot net" and the location of database and images should be "F:\programs\dot net\blog\blog\bin\Debug"

    Below I am showing some screen shots which would make things more clear.

     

     

    Above screen shot shows where your database is actually place and from this location we will place it our application directory location which is below:

    The above screen shot shows where we need to keep our database and images folder.

    Note: So far we have been using connection string-"@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=blog;Data Source=MY-PC\SQLEXPRESS";"

    But when we change location of our database, we will use our database as database file not as database in sqlserver.

    So, connection string changes to-"@"Data Source=.\SQLEXPRESS;AttachDbFilename="+System.Environment.CurrentDirectory +@"\blog.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";"

     

"System.Environment.CurrentDirectory" is giving us the system current directory and we are concatenating database file with it which eventually is giving us full location of our database which is "F:\programs\dot net\blog\blog\bin\Debug\blog.mdf".

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Data.SqlClient;

namespace blog

{

public partial class Form4_relative : Form

{

SqlConnection con;

string constr =@"Data Source=.\SQLEXPRESS;AttachDbFilename="+System.Environment.CurrentDirectory +@"\blog.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"

string sp_e_msg;

SqlCommand cmd;

SqlDataAdapter adpt;

DataTable dt;

int proc = 0;

string notific, fulllocimage,filename;

public Form4_relative()

{

InitializeComponent();

}

//******************browse button*********************************

private void button5_Click(object sender, EventArgs e)

{

openFileDialog1.ShowDialog();

 

fulllocimage = openFileDialog1.FileName;

filename = openFileDialog1.SafeFileName;

pictureBox1.ImageLocation = fulllocimage;

textBox3.Text = filename;

}

//***********************next>>****************************************

private void button1_Click(object sender, EventArgs e)

{

try

{

string folderPath = Path.GetDirectoryName(Application.ExecutablePath);

label4.Text = "";

con = new SqlConnection();

con.ConnectionString = constr;

con.Open();

cmd = new SqlCommand("blog_relative_select", con);

cmd.CommandType = CommandType.StoredProcedure;

//*************************************************************************

SqlParameter parm2 = new SqlParameter("@returnval", SqlDbType.Int);

parm2.Size = 50;

parm2.Direction = ParameterDirection.ReturnValue;

cmd.Parameters.Add(parm2);

//**************************************************************

SqlParameter parm1 = new SqlParameter("@msg", SqlDbType.VarChar);

parm1.Size = 50;

parm1.Direction = ParameterDirection.Output;

cmd.Parameters.Add(parm1);

//***************************************************************

adpt = new SqlDataAdapter(cmd);

dt = new DataTable();

adpt.Fill(dt);

if (dt.Rows.Count > 0)

{

textBox1.Text = dt.Rows[proc]["name"].ToString();

textBox2.Text = dt.Rows[proc]["ph"].ToString();

pictureBox1.ImageLocation =folderPath + @"\images\"+ dt.Rows[proc]["pic"].ToString();

proc = proc + 1;

 

cmd.ExecuteNonQuery();

notific = cmd.Parameters["@returnval"].Value.ToString();

//*************************************************************************

sp_e_msg = cmd.Parameters["@msg"].Value.ToString();

 

}

 

}

 

catch (Exception ex)

{

 

if (notific == "1")

{

label4.Text = sp_e_msg + notific+ ex.ToString() ;

}

}

finally

{

con.Close();

con.Dispose();

cmd.Dispose();

 

if (proc > dt.Rows.Count - 1)

{

label4.Text = "Records Ends";

proc = dt.Rows.Count - 1;

}

}

}

 

private void Form4_relative_Load(object sender, EventArgs e)

{

 

}

//*****************************insert*************************************

private void button3_Click(object sender, EventArgs e)

{

try

{

string folderPath = Path.GetDirectoryName(Application.ExecutablePath);

string tocpy = folderPath + @"\images\";

File.Copy(fulllocimage, tocpy + filename);

//***************************************************************************

con = new SqlConnection();

con.ConnectionString = constr;

con.Open();

 

cmd = new SqlCommand("blog_relative_insert", con);

cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = textBox1.Text;

cmd.Parameters.Add("@pic", SqlDbType.NVarChar).Value = textBox3.Text;

cmd.Parameters.Add("@ph", SqlDbType.NVarChar).Value = textBox2.Text;

//**************************************************************************

SqlParameter param = new SqlParameter("@returnval", SqlDbType.Int);

param.Size = 50;

param.Direction = ParameterDirection.ReturnValue;

//add to parameter to collection

cmd.Parameters.Add(param);

//***********************************************************************

SqlParameter param1 = new SqlParameter("@msg", SqlDbType.VarChar);

param1.Size = 50;

param1.Direction = ParameterDirection.Output;

//add to parameter to collection

cmd.Parameters.Add(param1);

//*************************************************************************

cmd.ExecuteNonQuery();

sp_e_msg = cmd.Parameters["@msg"].Value.ToString();

 

}

 

catch (Exception ex)

{

label4.Text = sp_e_msg + ex.ToString();

}

finally

{

con.Close();

con.Dispose();

cmd.Dispose();

 

}

}

 

//*************************<<previous**************************************

private void button2_Click(object sender, EventArgs e)

{

try

{

string folderPath = Path.GetDirectoryName(Application.ExecutablePath);

label4.Text = "";

con = new SqlConnection();

con.ConnectionString = constr;

con.Open();

cmd = new SqlCommand("blog_relative_select", con);

cmd.CommandType = CommandType.StoredProcedure;

//*************************************************************************

SqlParameter parm2 = new SqlParameter("@returnval", SqlDbType.Int);

parm2.Size = 50;

parm2.Direction = ParameterDirection.ReturnValue;

cmd.Parameters.Add(parm2);

//**************************************************************

SqlParameter parm1 = new SqlParameter("@msg", SqlDbType.VarChar);

parm1.Size = 50;

parm1.Direction = ParameterDirection.Output;

cmd.Parameters.Add(parm1);

//***************************************************************

adpt = new SqlDataAdapter(cmd);

dt = new DataTable();

adpt.Fill(dt);

if (dt.Rows.Count > 0)

{

textBox1.Text = dt.Rows[proc]["name"].ToString();

textBox2.Text = dt.Rows[proc]["ph"].ToString();

pictureBox1.ImageLocation = folderPath + @"\images\" + dt.Rows[proc]["pic"].ToString();

proc = proc - 1;

 

cmd.ExecuteNonQuery();

notific = cmd.Parameters["@returnval"].Value.ToString();

//*************************************************************************

sp_e_msg = cmd.Parameters["@msg"].Value.ToString();

 

}

 

}

 

catch (Exception ex)

{

 

if (notific == "1")

{

label4.Text = sp_e_msg + notific + ex.ToString();

}

}

finally

{

con.Close();

con.Dispose();

cmd.Dispose();

 

if (proc <0)

{

label4.Text = "Records Ends";

proc = 0;

}

}

}

}

}

 

Tags: , , ,

Windows Form