How to store and retrieve .pdf, .exe file in SQL Server 2008 - c#

I am currently working on a Windows Forms application (C#, VS 2010) and I need to create functionality that enables users to upload .pdf, .exe files into a SQL Server 2008 database and download them back.
The problem that I have is that the file downloaded from the database is always corrupted (except .txt file) even though they are the same size. And I have used varbinary(MAX) as the file type to store the data in the database.
Can anyone show me some example code for how to do this?
PS: I have researched for more than a week, but still cannot find a solution to my problem, can anyone please help? Any answer will be highly appreciated.

In the below example there are a few assumptions made:
I'm using Dapper for the database access. It extends any IDbConnection object.
I have a table in the database that has a definition as such CREATE TABLE Data (Id INT IDENTITY(1, 1) PRIMARY KEY, Data VARBINARY(MAX)).
Here is the documentation for ReadAllBytes
So, obviously since you didn't provide anything surrounding your table structure you're going to have to change this code to meet you needs, but it will get you started.
Writing It
this.connection.Open();
try
{
var parameters = new
{
Data = File.ReadAllBytes(...);
};
return connection.Execute("INSERT INTO Data (Data) VALUES (#Data)", parameters);
}
finally
{
this.connection.Close();
}
Reading It
this.connection.Open();
try
{
var parameters = new { Id = 1 };
return connection.Query(
"SELECT Data FROM dbo.Data WHERE Id = #Id", parameters)
.Select(q => q.Data as byte[])
.Single();
}
finally
{
this.connection.Close();
}

Related

How to read External Sqllite Database in xamirin android in Visual Studio C#

My Code :
var dbpath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "ot.db3");
Context myContext = null;
try
{
var dbcon = new SQLiteConnection(dbpath);
var db= dbcon.Query<records>("SELECT * FROM records WHERE sno = ? ", "1");
int count = db.Count;
}
catch (IOException ex)
{
var reason = string.Format("The database failed to create - reason {0}", ex.Message);
Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}
I Create a Sqlite Database from my SQL Server Database.
Now I save it to my Phone on this path (Android/Data/Application/File)
Now using Sqlite-net-pcl nugget package for Sqlite Connection the connection works fine showing have no error.
When I try to read a table from database this Give any error that "No Such Table exist in database". And the table exists in the database and is populated with data.
What can I do?
Thanks in advance
Why are you writing the SQL query? You could make it more simple, something like, conn.Get(id);
You will only need to add [PrimaryKey] to your PK in the model.
Also, I suggest you to not use SQLite.SQLiteConnection and use SQLiteAsyncConnection instead, so you will be able to get data using "await conn.GetAsync(id)" and this way it won't block the main thread.
Create a Blank Database – A database reference can be created by passing the file path the SQLiteConnection class constructor. You do not need to check if the file already exists – it will automatically be created if required, otherwise the existing database file will be opened.
var db = new SQLiteConnection (dbPath);
Save Data – Once you have created a SQLiteConnection object, database commands are executed by calling its methods, such as CreateTable and Insert like this:
db.CreateTable<Stock> ();
db.Insert (newStock); // after creating the newStock object
Retrieve Data – To retrieve an object (or a list of objects) use the following syntax:
var stock = db.Get<Stock>(5); // primary key id of 5
var stockList = db.Table<Stock>();
For more info use following link:
https://developer.xamarin.com/guides/android/application_fundamentals/data/part_3_using_sqlite_orm/#Using_SQLite.NET
You need to check in your DB file if the table really exists.
Extract the database from your Android device/simulator with ADB
Example: adb pull //.db .
It will download the DB file to your computer.
Then, use a tool such as "DB Browser for SQLite" (http://sqlitebrowser.org/) to open your DB file and check if your table exists.
Other common mistakes when using SQLite with Android are:
the file is not found (the path in your connectionstring is not good)
the name is not the one your think (maybe in your case, it is "Record" and not "Records")
Hope it will help.

Ado.net firebird commit insert new lines to table

I'm adding new lines to a database for our company's "order list" for each order created, using the firebird ado.net client. The code i've written works fine for listing items, but inserting new ones doesn't appear elsewhere (e.g. in flamerobin). What I think is happening is that the transaction isn't being committed, seeing as it's recognised within my code (can't add duplicate values).
Code:
using (FbConnection fbCon = new FbConnection)
{
fbCon.Open();
***command w/ parameterised command string***
using (FbTransaction fbTrans = fbCon.BeginTransaction())
using FbCommand orderCommand = new FbCommand(cmdString, fbCon, fbTrans)
{
***Adding parameters and values***
try
{
int recordsAffected = orderCommand.ExecuteNonQuery();
fbTrans.Commit();
}
catch (FbException E)
{
fbTrans.Rollback();
fbCon.Close();
throw E
}
}
recordsAffected returns 1 but I am not able to see the updated values in flamerobin or the db management program. Am i missing something?
If anyone else runs into this problem, it's in Visual Studio's debugging settings. https://visualstudiomagazine.com/blogs/tool-tracker/2012/05/dealing-with-local-databases-or-why-your-updates-dont-stick.aspx explains pretty clearly, but basically VS makes a copy of your database in bin/Debug of your project (Ostensibly to not mess with your data) but if you actually need to use/view the data externally, either link your external application to the debug database (e.g. flamerobin). You may also need to set your project database settings to Copy if Newer if you want your updates to stay, as the default setting copies the database into the folder each time you run your c# app.

SQL Sever 2014 Query Notifications in C++ with ADO.NET libraries

I have a C++ application that has to react to status changes that are kept in an SQL database. They have to react in real-time, and currently this is done by polling. However the real-time response time I need is overloading the database.
I have read about Query Notifications introduced in SQL Server 2005, but in truth I don't really understand the different SQL connection methods available. Currently I use ADO.NET to faciliate database communication, but the only sample code I have found for doing Query Notifications of this nature is in C# and VB. Not to mention that I am struggling to understand the concept. Here is a sample of how I currently run SQL with ADO.NET.
hr = link.CreateInstance(__uuidof(Connection) );
if (link) { // Execute the query on the open connection using existing command object
pCommand.CreateInstance(__uuidof(Command));
pCommand->ActiveConnection = link;
pCommand->CommandType = ado20CommandType;
pCommand->CommandText = strQuery.GetBuffer(0);
pCommand->PutPrepared(true);
pCommand->NamedParameters = true;
if (pRecordSet = pCommand->Execute(&vRecordsAffected,NULL,NULL)) { // Execute the final query and set object-level recordset object
lRecordsAffected = vRecordsAffected.lVal;
_RecordsetPtr pfuRecordSet = link->Execute(_T("SELECT ##IDENTITY as pmIDENT;"),NULL,adCmdText);
CString strID = pfuRecordSet->GetFields()->GetItem(COleVariant("pmIDENT"))->Value.bstrVal;
int nID = atoi(strID);
if (nID > 0) {
nLastInsertedID = nID;
}
return true;
}
I was wondering if someone could provide me with resources and/or sample code that would help me set this up in C++? Thanks in advance.
The fastest way to get data out of a SQL Server database is using the SqlDataReader, which is forward-only, read-only.
Take a look at this C++ code and give that a try.
http://tinyurl.com/m6u9jh7

Use SQL in C# to get a Database's Drive Letter

I am trying to find out what drive a database is on, on the server. To further elaborate, there is a sever "MyServer" and three databases on that server. Databases A and B are on the "C:\" Drive of that server and database C is on the "D:\" Drive. I want to know how I can use the connection string to try and get the drive letter so that when a user selects a database from an application it tells them what drive that database is on.
Currently I am trying the following means and not getting the correct response:
Private void GetDriveLetter()
{
string connectionString = String.Format(DatabaseInfo.CONNECTIONSTRING_TEMPLATE, dbName, server)
try
{
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
cn.Open();
Server srv = new Server(new ServerConnection(cn));
Database database = new Database(srv, dbName);
txtDriveLetter.Text = database.PrimaryFilePath;
cn.Close();
}
}
catch (Exception ex)
{
myException = ex.Message
}
}
DatabaseInfo is just a class we use for reading SQL Servers and database names, and myException is a function that writes exceptions to a log file. The issue I am having is that no matter what I do I get an exception that says PrimaryFilePath is never set. Am I doing something wrong/missing something, or is this just not the correct way to go about this?
EDIT: Sorry never posted the exception
To accomplish this action, set property PrimaryFilePath.
You could always run a query against your sys catalog views inside SQL Server:
SELECT * FROM sys.master_files
This will list your database, it's id, its logical name, and the location of the file on disk.
You should probably access the existing database, rather than constructing a new one:
Database database = srv.Databases[dbName];
(Of course, error handling required if the name doesn't exist).
Also, of course, you should be aware that a database may consist of multiple files, and those files may be on different drives.
If this is SQL Server, then you can use
SELECT * FROM sys.database_files
to get the files of the current database. So, your connection string should connect you to the database that you want and then the above SQL will give you lots of information that you might find useful, including the physical_name. From that you can extract the drive letter.

Modify .mdf file from a wpf application using C#

I am using VS2010 , and I am building a simple wpf application using C#
I have built a database using SQL Server 2008
in my application I created a LINQ to SQL class and created a dbml file
then I created a datacontect and did everything right
BUT
when I can't aaccess my database file everytime I try to , I mean when I insert anew row in my datacontexct I can check it and see it but when I look in my mdf file I can't find anything
I think that my datacontexct must be connected to my database file somehow
please help me because I seriously need it
The connection string, that is passed to the datacontext, references the MDF.
// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(#"northwnd.mdf");
var cityNameQuery =
from cust in nw.Customers
where cust.City.Contains("London")
select cust;
foreach (var customer in cityNameQuery)
{
if (customer.City == "London")
{
customer.City = "London - Metro";
}
}
// you must call this this commit the changes
nw.SubmitChanges();
Call .SubmitChanges() on your DataContext after adding an item.

Categories

Resources