How to create a connection string outside web.config - c#

Just thinking about this, is it possible to create a connection string outside the ASP.NET's web.config?

Possibly you're looking for configSource?

Yes you can store it anywhere it is just text.... The web.config is just a XML document that stores configuration settings about your application. You could just as easily create another XML file or a text file and read it in from there. You just wouldnt be able to use:
ConfigurationManager.ConnectionStrings[].ConnectionString

You can create a connection string through the usage of .udl file.
UDL File Creation :
Right-click on the desktop, or in the folder where you want to create the file.
Select New, then Text Document.
Give the Text Document any name with a .udl extension ("Show file extensions" must be enabled in folder options).
A window will pop up warning that "If you change a filename extension, the file may become unusable. Are you sure you want to change it?" Select Yes.
You have now successfully created a UDL file.
Now you need to implement the settings inside the .udl file according to your requirements. A video tutorial has been provided to explain you the whole procedure of using .udl file to create a connection string for MS SQL Server.
http://visiontechno.net/studymats/udlcreation.html

You can have it in another .config file that gets pulled in by your web.config like this:
<appSettings file="../Support/config/WebEnvironment.config">
</appSettings>
You can then use it in your code like this:
System.Configuration.ConfigurationManager.AppSettings["DefaultConnection"]
We have it such that this file isn't physically under our site, but it is virtually under it. That is the "Support" directory above is a virtual directory. Details can be found HERE.

You can use following in case of MSSQL server
string connectionString = "Your Connection string"
using (SqlConnection con = new SqlConnection(connectionString))
{
//
// Open the SqlConnection.
//
con.Open();
//
// The following code uses an SqlCommand based on the SqlConnection.
//
using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
}
}

Related

Storing Images in Project Folder - Directory Not Found Error Message

I am trying to save images to a SlideImages folder in my ASP.NET web forms website, using C#.
When I try to submit an image using the following code:
protected void btnSubmitImage_Click(object sender, EventArgs e)
{
//Get Filename from fileupload control
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
//Save images into SlideImages folder
fileuploadimages.SaveAs(Server.MapPath("SlideImages/" + filename));
//Open the database connection
con7.Open();
//Query to insert images name and Description into database
SqlCommand cmd = new SqlCommand("Insert into SlideShowTable(ImageName,Description) values(#ImageName,#Description)", con7);
//Passing parameters to query
cmd.Parameters.AddWithValue("#ImageName", filename);
cmd.Parameters.AddWithValue("#Description", txtDesc.Text);
cmd.ExecuteNonQuery();
//Close dbconnection
con7.Close();
txtDesc.Text = string.Empty;
BindDataList();
}
I get the below error message when trying to execute the 4th line of the code above.
An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code. Additional information: Could not find a part of the path 'C:\Users\11342\OneDrive\Documents\4th Year\FYP\BallinoraWaterfallCommunity\SlideImages\'.
Here is my project folder structure. I am trying to store the images in the SlideImages folder of my project.
I managed to successfully store images in the 'Images' folder using the below code. I have tried to adapt it to fix the above problem, but I have not been able to.
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Get Filename from fileupload control
string filename = Path.GetFileName(fileuploadimages.PostedFile.FileName);
//Save images into Images folder
fileuploadimages.SaveAs(Server.MapPath("Images/" + filename));
//Getting dbconnection from web.config connectionstring
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BallinoraDBConnectionString1"].ToString());
//Open the database connection
con.Open();
//Query to insert images path and name into database
SqlCommand cmd = new SqlCommand("Insert into Group_Images(ImageName,ImagePath) values(#ImageName,#ImagePath)", con);
//Passing parameters to query
cmd.Parameters.AddWithValue("#ImageName", filename);
cmd.Parameters.AddWithValue("#ImagePath", "Images/" + filename);
cmd.ExecuteNonQuery();
//Close dbconnection
con.Close();
Response.Redirect("~/Admin.aspx");
}
You should use Server.MapPath("~/SlideImages). Notice the ~/ prefix which forces the mappath to start at the root of the web application.
Then add the file name as the file does not exist yet on disk but you should use System.IO.Path.Combine to combine the mapped root website path (and images folder) with the file name.
Also you should check if the directory exists or not. In your screen shot you have content in Images so this folder is probably being copied to your destination website path when you deploy. The other one is empty, it might not be created when you deploy your application because there is no content to copy.
Here is the modified code, check if it exists and create it if it does not. You should verify the web application's user context has sufficient privileges to create a directory in the root website directory.
var directory = Server.MapPath("~/SlideImages");
if(!System.IO.Directory.Exists(directory))
System.IO.Directory.Create(directory);
fileuploadimages.SaveAs(System.IO.Path.Combine(directory, filename));
Side note
You should wrap any instances that implement IDisposable with using blocks or make sure that they are disposed of in the dispose method of the containing type. I noticed in your 2nd example you created a SqlConnection instance and then called close later which is not good practice. Why that is is because if you have an Exception that occurs your SqlConnection, SqlCommand, or anything else that needs to clean up resources will stick around longer than needed which can cause issues later on like exceeding the max number of simultaneous allowed open connections to a Sql Server or not being able to serve an image because there is a lock on the file.

Unable to find table after successfully connecting to database file

I'm currently a console application tool using C# where user is allowed to input the directory of the database file (which is located somewhere on the desktop), and I am required to get the .db file from the specified location and connect it followed by retrieving it's content from the table into a text file. However I'm getting a SQLite error stating that the table is not found. And whenever I run the code, It creates a copy of the .db file but its empty.
But this error doesn't show when I manually 'copy-paste' a copy of the .db file in my debug folder. So I'm wondering is it a must to keep a copy in the debug folder or is there any other way to allow something like a remote connection. (FYI. I'm really new to C# and SQLite).
connectionString = "DataSource=myDataBase.db";
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
using (SQLiteCommand command = new SQLiteCommand("SELECT File,Path FROM Structure", connection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//Do some stuffs
}
reader.Close();
connection.Close();
}
}
}
Without a file path, the database file will be searched for in the current directory (whatever it happens to be).
When the database file does not exist, SQLite will happily create a new, empty one.
Include the complete directory in the connection string:
connectionString = "DataSource=C:\\some\\where\\myDataBase.db";

Need some clarification about app.config and user.config

So I have been poking around both here on SO and google for the last few days for information about app.config.
I am writing a program that will need to generate SQL scripts using values entered by a user. Originally I was using app.config to store some default values to load into the program when it is first started up. This worked fine until I tried to store the new values back into the app.config file. This is when I found that app.config is read only and I should have been using user.config.
I have several questions that I can't seem to find the answers to:
Is it recommended to use settings.Setting to declare all the values that I want to use app.config? Or is entering them in by hand is enough?
I keep reading about how user.config overrides app.config settings. But when I update my user.config file, the program still reads from the original app.config file
This is from my wrapper class
public NameValueCollection ReadSettings(string sectionName)
{
NameValueCollection scripts = null;
try
{
//read in the current values from the section
scripts = (NameValueCollection)ConfigurationManager.GetSection(sectionName);
if (scripts == null) throw new appConfigException(String.Format("The section {0} does not exists in app.config", sectionName));
}catch (Exception e){
//print out the log file
StreamWriter writer = new StreamWriter(DateTime.Now.ToString("d-MMM-yyyy") + "log.txt");
writer.WriteLine(e.ToString());
writer.Close();
//kill the application process so the user cannot advance further
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
return scripts;
}
is the ConfigurationManager supposed to automatically know to start reading from the user.config? Or do I need to change this section of code to reflect that?
Question 1: It is easier to use Settings.settings instead of creating your own configuration file yourApp.config. Because using the first option you can access your properties just using Properties.Settings.Default.MyProperty and with the app.config file instead you have to deal with ConfigurationManager object, and usually to access a property you need to know the name beforehand and it usually is hardcoded.
Question 2: Yes, you are right the app.config is different from Settings.setting. Because you could even create a new file temp.config which could also be used as a config file for your application.
Final question: Im not sure, but I don't think ConfigurationManager knows anything about that, just parse the app.config file.
Hope it helps.

Reading A Fixed Format Text File

Its been years since I have had to attempt to read a file using either Microsoft Text ODBC Driver or Microsoft Jet OLE DB 4.0 Provider.
So I have the following code
public void Example()
{
string CVS = Application.StartupPath;
string SQL = "SELECT * FROM [MyFile.txt]";
string Connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+CVS+";"+"Extended Properties='text;HDR=Yes;FMT=Fixed;";
OleDbDataAdapter OLE = new OleDbDataAdapter(SQL,Connection);
DataTable Table = new DataTable();
OLE.Fill(Table);
}
When I run the above code I get an "Unexpected Error", I know I am missing something, I am not sure what exactly.
Sources:
http://www.connectionstrings.com/textfile
http://www.connectionstrings.com/Providers/net-framework-data-provider-for-ole-db
http://www.aspdotnetcodes.com/Importing_CSV_Database_Schema.ini.aspx
Any direction would be appreciated.
Let us assume the Schema.ini file is correct.
Remove ' (just prior to 'text;) from the connection string.
In order to resolve the "Could not find installable ISAM", run the following command:
Regsvr32 c:\winnt\system32\mstext40.dll
* Make sure that file is in that folder first. And change WINNT to whatever your windows directory is.
I know this is not a real answer to your question, but i would really rethink about using this architecture to read in a file.
I would really prefer something like CSV Reader, cause it gives you much more power about how the data will be interpreted. Alternative you could also take a look into the FileHelpers.

New Access database, how can it be done?

I have a project in C# using Microsoft Office Access for storage. I can read and save to the database.
Now I need to allow the user to use the new database project but structured like the working one, and also to implement Save As option.
Besides I need to export to a text file/CSV.
Any ideas or sample codes would be helpful.
One way to create a blank DB is to try the following
using System;
using ADOX;
public class CreateDB
{
public static void Main( string [] args )
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();
string create =
#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\BlankAccessDB\MyAccessDBCreatedFromCsharp.mdb;" +
"Jet OLEDB:Engine Type=5";
cat.Create(create);
cat = null;
}
}
Both Save and SaveAs is as easy as using SaveFileDialog to prompt the user to specify the filename and location to save the file.
The way I did this was to create a new empty access database file (this comes to about 100 KB) and then embed that file as a resource in my application. To "create" a new database is then simply a matter of extracting the resource to a file - which gives you a blank database - and then running a schema update code to create the schema you require in the blank database and then off you go.
I have a project that contains an empty database set to be embedded, a class with one method as below and, er, that's about it.
This is the code to dump the file from the embedded resource - it's not up to date, I wrote it 6 years ago but have had no need to change it:
public void CreateDatabase(string sPath)
{
// Get the resource and, er write it out?
System.IO.Stream DBStream;
System.IO.StreamReader dbReader;
System.IO.FileStream OutputStream;
OutputStream = new FileStream(sPath, FileMode.Create);
Assembly ass = System.Reflection.Assembly.GetAssembly(this.GetType());
DBStream = ass.GetManifestResourceStream("SoftwareByMurph.blank.mdb");
dbReader = new StreamReader(DBStream);
for(int l=0;l < DBStream.Length;l++)
{
OutputStream.WriteByte((byte)DBStream.ReadByte());
}
OutputStream.Close();
}
Simple, effective and the .dll is 124 KB.
Note I use an utterly blank and empty Access file - attempting to maintain the right schema in the embedded file is going to cause it to grow (because of the way .mdb files work) and may result in shipping data - which probably shouldn't happen. The schema itself is created/updated/maintained by a separate lump of DDL (SQL) that I run from code.
Export to .CSV is moderately trivial to do by hand since you pretty much just need to iterate over the columns in a table but for a smarter approach look at FileHelpers.

Categories