Store .txt files into Mysql as Blob from ASP.Net MVC3 - mysql

Currently I'm Working on ASP.NET MVC 3 Project. I need to Store text(.txt) files into MySQL as Blob. MySQL is New to me.

Should be something like this (Connectionstring should be modified):
string filePath = #"C:\\MyFile.ext";
//A stream of bytes that represnts the binary file
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
//The reader reads the binary data from the file stream
BinaryReader reader = new BinaryReader(fs);
//Bytes from the binary reader stored in BlobValue array
byte[] BlobValue = reader.ReadBytes((int)fs.Length);
fs.Close();
reader.Close();
SqlConnection BlobsDatabaseConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");
SqlCommand SaveBlobeCommand = new SqlCommand();
SaveBlobeCommand.Connection = BlobsDatabaseConn;
SaveBlobeCommand.CommandType = CommandType.Text;
SaveBlobeCommand.CommandText = "INSERT INTO BlobsTable(BlobFileName, BlobFile)" + "VALUES (#BlobFileName, #BlobFile)";
SqlParameter BlobFileNameParam = new SqlParameter("#BlobFileName", SqlDbType.NChar);
SqlParameter BlobFileParam = new SqlParameter("#BlobFile", SqlDbType.Binary);
SaveBlobeCommand.Parameters.Add(BlobFileNameParam);
SaveBlobeCommand.Parameters.Add(BlobFileParam);
BlobFileNameParam.Value = filePath.Substring(filePath.LastIndexOf("\\") + 1);
BlobFileParam.Value = BlobValue;
try
{
SaveBlobeCommand.Connection.Open();
SaveBlobeCommand.ExecuteNonQuery();
MessageBox.Show(BlobFileNameParam.Value.ToString() + " saved to database.","BLOB Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
SaveBlobeCommand.Connection.Close();
}
Take a look at:
Writing BLOB Values to a Database

Related

Display or Download Documents Saved in SQL Server with ASP.NET

I have documents saved in a SQL Server database as varbinary(MAX).
I am trying to retrieve the document from the database with below code. The problem I am facing is that no matter the browser I use, I don't get any response back. No dialog the browser just displays the turning circle.
Any suggestions would be highly appreciated..
if (e.ButtonID != "Download")
return;
int id = 2;
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["bexsConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Title, WillData, MIMEType from Will_documents where Doc_id = #Id";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["WillData"];
contentType = sdr["MIMEType"].ToString();
fileName = sdr["Title"].ToString();
Response.Buffer = true;
Response.Charset = "";
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
con.Close();
}
}
Eventually got it Working.
Response.ClearContent();
Response.ContentType = "application/octetstream";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", name));
Response.AddHeader("Content-Length", documentBytes.Length.ToString());
Response.BinaryWrite(documentBytes);
Response.Flush();
Response.Close();

Xamarin SqlConnection throwing error Input string was not in correct format

Im trying to connect my mobile to PC database using this code:
string cString = #"Persist Security Info=False;Integrated Security=false;Initial Catalog=myDB;server=192.168.1.11,1433\SqlExpress";
SqlConnection connection = new SqlConnection(cString);
connection.Open();
using (SqlCommand cmd = new SqlCommand("SELECT name1 FROM Product", connection))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
t.Text += rdr.GetString(rdr.GetOrdinal("name1")) + System.Environment.NewLine;
}
}
}
Unfortunately I'm getting error: "Input string was not in the correcr format", source: mscorlib.
I know that there's error in connectionString (throwin exception after connection.Open())
Any ideas? Thanks in advance!
your current Culture is not in correct format
protected override void OnResume()
{
base.OnResume();
//Here you would read it from where ever.
var userSelectedCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = userSelectedCulture;
}

WP8 - SkyDrive API Uploading files error

Basically I'm having this problem. So I've created a folder in skydrive from my app and I want to upload a textfile to that folder but it simply isn't letting me. Bascailly the only way i can upload the textfile is if i set the location to "me/skydrive". I wan't it so that the textfile gets uploaded to a folder on SkyDrive called "Pencil Notes".
My code soo far is:
Dim myIsolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim mp1 = TryCast(App.RootFrame.Content, MainMenu)
Dim dataSource As New List(Of SampleData1)()
Dim data = TryCast(ItemsListSkyDrive.SelectedItem, SampleData1)
Dim writeFile As New StreamWriter(New IsolatedStorageFileStream("/shared/transfers/" & data.Name & ".txt", FileMode.Create, myIsolatedStorage))
Dim Title As String = data.Name
Dim Message As String = data.Description
writeFile.WriteLine(Title)
writeFile.WriteLine(Message)
writeFile.Close()
Dim store1 As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Using store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Try
Dim res As LiveOperationResult = Await client.BackgroundUploadAsync("me/skydrive/Pencil Notes", New Uri("/shared/transfers/" & data.Name & ".txt", UriKind.Relative), OverwriteOption.Overwrite)
MessageBox.Show("Done", "", MessageBoxButton.OK)
store1.DeleteFile("/shared/transfers/" & data.Name & ".txt")
Catch ex As Exception
MessageBox.Show(ex.Message, "", MessageBoxButton.OK)
End Try
End Using
This PostCompleted event is use to upload your files in skydrive:
client.PostCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(CreateMyFolder_Completed);
void CreateMyFolder_Completed(object sender, LiveOperationCompletedEventArgs e)
{
if (e.Error == null)
{
string folderID = (e.Result["id"]).ToString();
foreach (string item in names)
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
string filename = item;
if (store.FileExists(filename))
{
IsolatedStorageFileStream storeStream = store.OpenFile(filename, FileMode.Open, FileAccess.Read);
client.UploadAsync(folderID, filename, storeStream, OverwriteOption.Overwrite);
}
}
}
}
This would help you

How to get list of reports

How to list all the reports, that I have created in the report server? Later I would like to use this list to display them in my ReportViewer control.
Report server uses stored procedure called FindObjectsNonRecursive.
string cnxstr = "Data Source=server;Initial Catalog=ReportServer;Integrated Security=SSPI;"; //connection string
using (SqlConnection connection = new SqlConnection(cnxstr))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "FindObjectsNonRecursive";
command.Parameters.Add(new SqlParameter("#Path", "/folder_name"));
command.Parameters.Add(new SqlParameter("#AuthType", 1));
SqlDataReader reader = null;
try
{
reader = command.ExecuteReader();
while (reader.Read())
{
string path = reader["Path"].ToString();
//now you can display this path in your list, or do whatever
}
}
finally
{
if (reader != null)
reader.Close();
}
}

Access import into SQL server not importing first line

I am using a function to import data from a access db into SQL server:
public string importDataFromAccess(string table, string fileName)
{
OleDbConnection OleDbConn = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", fileName));
try
{
string sSQLTable = table;
string myExcelDataQuery = "Select * from " + sSQLTable;
string sSqlConnectionString = connStr;
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
SqlConn.Close();
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);
OleDbConn.Open();
OleDbDataReader dr = OleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.DestinationTableName = sSQLTable;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
OleDbConn.Close();
return "Done";
}
catch (Exception ex)
{
OleDbConn.Close();
return ex.ToString();
}
}
I noticed it isnt importing the first record of each table, can anyone help notice why and how to fix? Hopefully it is only the first row...
You shouldn't need the
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
And you just need to replace that with
bulkCopy.WriteToServer(dr);
The WriteToServer method
Copies all rows in the supplied IDataReader to a destination table
specified by the DestinationTableName property of the SqlBulkCopy
object.
But the dr.Read() that you have called has read the first line out of the Reader and advanced the IDataReader to the next record (so it is not accessible to the WriteServer method).