I get an error in my code - sql

I got an error
Incorrect syntax near '.'. Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using System.Threading;
namespace Cloths_Inventory
{
public partial class frmBackup : Form
{
//DataTable dtServers = SmoApplication.EnumAvailableSqlServers(true);
//private static Server srvr;
//private string DBpath = Application.StartupPath;
public frmBackup()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bool bBackUpStatus = true;
Cursor.Current = Cursors.WaitCursor;
if (Directory.Exists(#"D:\SQLBackup"))
{
if (File.Exists(#"D:\SQLBackup\wcBackUp1.bak"))
{
if (MessageBox.Show(#"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
File.Delete(#"D:\SQLBackup\wcBackUp1.bak");
}
else
bBackUpStatus = false;
}
}
else
Directory.CreateDirectory(#"D:\SQLBackup");
if (bBackUpStatus)
{
//Connect to DB
SqlConnection connect;
string con = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Garment.mdf;Integrated Security=True;Asynchronous Processing= True ;User Instance=True";
connect = new SqlConnection(con);
connect.Open();
//Execute SQL---------------
SqlCommand command;
command = new SqlCommand(#"backup database Garment.mdf to disk ='E:Garment.bak' with init,stats=10", connect);
command.ExecuteNonQuery();
//--------------
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}

You cannot use the AttachDbFileName= approach and then use a server-based command like backup database....
If you want to back up your SQL Server database, it has to be attached to the server, and you need to connect to the server and issue that command:
// Connect to "master" database
string con = #"server=.\SQLEXPRESS;database=master;Integrated Security=True;";
SqlConnection connect = new SqlConnection(con);
SqlCommand ommand = new SqlCommand(#"backup database Garment to disk = N'E:\Garment.bak' with init,stats=10", connect);
connect.Open();
command.ExecuteNonQuery();
connect.Close();

You are missing a backslash E:Garment.bak should be E:\Garment.bak
command = new SqlCommand(#"backup database Garment.mdf to disk ='E:\Garment.bak' with init,stats=10", connect);

Related

The Microsoft Access database engine cannot open or write to the file

I have the following function:
Public Function OleDBCSVToDataTable(directory As String, tableName As String, fileName As String, Optional start As Long = 0) As DataTable
Dim CnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & directory & ";Extended Properties='Excel 8.0;HDR=YES'"
Dim dt As DataTable = GetTableSchema(tableName)
Using Adp As New OleDbDataAdapter("select * from [" & fileName & "]", CnStr)
Adp.Fill(start, 1000, dt)
End Using
Return dt
End Function
The function is designed to read a CSV into a data table using OLEDB for import into SQL, however I am receiving this error:
"The Microsoft Access database engine cannot open or write to the file
'C:\TEST'. It is already opened exclusively by another user, or you
need permission to view and write its data."
I have attempted this solution. All permissions have been granted (permissions are Full Control across users):
I have seen this solution as well, however, the proposed options other than OLEDB are solutions that don't seem to work with CSV. Besides, I imagine there are native libraries.
I am open to suggestions for better ways to accomplish this, however, based on requirements - large CSVs, data validation - this appears to be the best, assuming I am able to get it working.
How about importing the CSV file into a DataGridView, and then exporting from that object into MS Access?
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.Globalization;
using System.Configuration;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
string delimiter = ",";
string tablename = "medTable";
DataSet dataset = new DataSet();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "CSV Files (*.csv)|*.csv|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (MessageBox.Show("Are you sure you want to import the data from \n " + openFileDialog1.FileName + "?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
filename = openFileDialog1.FileName;
StreamReader sr = new StreamReader(filename);
string csv = File.ReadAllText(openFileDialog1.FileName);
dataset.Tables.Add(tablename);
dataset.Tables[tablename].Columns.Add("Order ID");
dataset.Tables[tablename].Columns.Add("Product");
dataset.Tables[tablename].Columns.Add("Unit Price");
dataset.Tables[tablename].Columns.Add("Quantity");
dataset.Tables[tablename].Columns.Add("Discount");
string allData = sr.ReadToEnd();
string[] rows = allData.Split("\r".ToCharArray());
foreach (string r in rows)
{
string[] items = r.Split(delimiter.ToCharArray());
dataset.Tables[tablename].Rows.Add(items);
}
this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;
MessageBox.Show(filename + " was successfully imported. \n Please review all data before sending it to the database.", "Success!", MessageBoxButtons.OK);
}
else
{
this.Close();
}
}
}
public string filename { get; set; }
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void Import_Load(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
//remove the semicolon, and add brackets below after line
{
//create the connection string
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Ryan\\Desktop\\Coding\\Microsoft Access\\Northwind_2012.mdb";
//create the database query
string query = "SELECT * FROM [OrderDetailsTest]";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
//the DataGridView
DataGridView dataGridView1 = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridView1.DataSource = bSource;
// An update function to get the changes back into the database.
dAdapter.Update(dTable);
}
}
}

Multiple SqlCommand in one SqlConnection "unreachable code detected" because of return

I have built a repository for my realtime dashboard with 1 SqlCommand and 1 SqlConnection. My intent is to add more SQL commands to my existing code.
However, the problem is the return statement inside the SqlCommand which disables any other SqlCommand afterwards.
Can anyone help me to make this code below work.
This is the full code:
using MVCRealtime;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace MVCRealtime
{
public class LocationInfoRepository
{
public IEnumerable<LocationInfo> GetData()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT ...", connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
using (var reader = command.ExecuteReader())
{
return reader.Cast<IDataRecord>().Select(x => new LocationInfo()
{
Names = x.GetString(0),
Values = Math.Round(x.GetDouble(1), 2).ToString("#,##0.00"),
ValuesDouble = x.GetDouble(1)
}).ToList();
}
}
using (SqlCommand command2 = new SqlCommand(#"SELECT... ", connection))
{
command2.Notification = null;
SqlDependency dependency = new SqlDependency(command2);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
using (var reader = command2.ExecuteReader())
{
return reader.Cast<IDataRecord>().Select(x => new LocationInfo()
{
Names2 = x.GetString(0),
Values2 = Math.Round(x.GetDouble(1), 2).ToString("#,##0.00"),
ValuesDouble2 = x.GetDouble(1)
}).ToList();
}
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
MyHub.Show();
}
}
}
This part is what i need help with(remove return):
return reader.Cast<IDataRecord>()
.Select(x => new LocationInfo()
{
Names = x.GetString(0),
Values = Math.Round(x.GetDouble(1), 2).ToString("#,##0.00"),
ValuesDouble = x.GetDouble(1)
}).ToList();
}
I just don't know how to use the
return reader.Cast<IDataRecord>().Select(x => new LocationInfo()
without the return

"The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value...." How to Fix Code in .cs file

I'm getting this error on my .Cs Log file. cant understand why this showing now.
the error says its in Line 43
Another issue is that this code sometimes for this project is that it logs in fine sometimes, sometimes its giving the above error.
Here is my LogApplication.cs code.
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
using System.Drawing;using System.Data;
namespace YCT.Moderator
{
public class LogApplication
{
public static void LogApplicationActivity(string IPAddress, string timestamp, string username, string activity, string urlcurrent, string referrerurl, string useragent)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
try
{
using (SqlCommand cmd1 = new SqlCommand())
{
cmd1.CommandText = "insert into LogApplication(IPAddress,TimeStamp,Username,Activity,URLCurrent,ReferrerURL,UserAgent) values (#IPAddress,#TimeStamp,#Username,#Activity,#URLCurrent,#ReferrerURL,#UserAgent)";
cmd1.Parameters.AddWithValue("#IPAddress", IPAddress);
cmd1.Parameters.AddWithValue("#TimeStamp", timestamp);
cmd1.Parameters.AddWithValue("#Username", username);
cmd1.Parameters.AddWithValue("#Activity", activity);
cmd1.Parameters.AddWithValue("#URLCurrent", urlcurrent);
cmd1.Parameters.AddWithValue("#ReferrerURL", referrerurl);
cmd1.Parameters.AddWithValue("#UserAgent", useragent);
cmd1.Connection = con;
con.Open();
cmd1.ExecuteNonQuery();
}
}
catch
{
throw;
}
finally
{
con.Close();
}
}
public static string RetrieveLatestLoggedinActivity(string username, string activity)
{
string value = "";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
try
{
using (SqlCommand cmd1 = new SqlCommand())
{
cmd1.CommandText = "select top 1 timestamp from LOGAPPLICATION where username=#Username and activity=#Activity order by timestamp desc ";
cmd1.Parameters.AddWithValue("#Username", username);
cmd1.Parameters.AddWithValue("#Activity", activity);
cmd1.Connection = con;
cmd1.Connection = con;
con.Open();
if (cmd1.ExecuteScalar() != null)
value = cmd1.ExecuteScalar().ToString();
}
}
catch
{
throw;
}
finally
{
con.Close();
}
return value;
// return dt;
}
}
}

export table sql to .txt with c#

I think I have a fairly simple question. I just need to know how to export fields from a table in an sql database using either asp.net or C#? Anyway to do this would be good.
I suppose I am looking for something like this, but perhaps simpler:
Export values from SQL Server to txt file
Whatever the case, I am trying to get values from a database to a .txt, like by pressing a button in asp.net or C#, based on criteria (like between certain dates, from a date field, or starting at a certain date with a certain user, and exporting a certain number of them). Any suggestions would help.
If I used the following code, what would I need to change so that if I wanted to select a certain column, like Note, in the database, and Date column, what would I need to do?
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class ExportText : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MYLearningConnectionString"].ConnectionString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from tblUsers", conn);
DataSet ds = new DataSet();
da.Fill(ds);
ExportToText(ds.Tables[0], "DataTable");
}
protected void ExportToText(DataTable dataTable, string fileName)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
foreach (DataColumn column in dataTable.Columns)
{
context.Response.Write(column.ColumnName + ",");
}
context.Response.Write(Environment.NewLine);
foreach (DataRow row in dataTable.Rows)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
context.Response.Write(row[i].ToString() + ",");
}
context.Response.Write(Environment.NewLine);
}
context.Response.ContentType = "text/csv";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");
context.Response.End();
}
}

DataSync In Mvc4 for Two Different User

I am trying to sync two database of a sql in mvc4 website?
i have this code to sync it is showing no error but it is not getting executing
using Microsoft.Synchronization;
using Microsoft.Synchronization.Data;
using Microsoft.Synchronization.Data.SqlServer;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Planetskool.Controllers
{
public class DataSyncViewController : Controller
{
//
// GET: /DataSyncView/
public ActionResult Index()
{
string sqlazureConnectionString = "Server=(LocalDb)\v11.0;Initial Catalog=aspnet-Planetskool-20130901224447;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-20130901224447.mdf";
string sqllocalConnectionString = "Server=(LocalDb)\v11.0;Initial Catalog=aspnet-Planetskool-20130901224446;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-20130901224446.mdf";
using (SqlConnection serverCon = new SqlConnection(sqlazureConnectionString))
using (SqlConnection clientCon = new SqlConnection(sqllocalConnectionString))
{
var provider1 = new SqlSyncProvider("scope1", serverCon);
var provider2 = new SqlSyncProvider("scope1", clientCon);
prepareServer(provider1);
prepareClinet(provider2, serverCon);
SyncOrchestrator sync = new SyncOrchestrator();
sync.LocalProvider = provider1;
sync.RemoteProvider = provider2;
sync.Synchronize();
return View();
}}
private static void prepareServer(SqlSyncProvider provider)
{
SqlConnection connection = (SqlConnection)provider.Connection;
SqlSyncScopeProvisioning config = new SqlSyncScopeProvisioning(connection);
if (!config.ScopeExists(provider.ScopeName))
{
DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(provider.ScopeName);
scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Author_Master", connection));
config.PopulateFromScopeDescription(scopeDesc);
config.SetCreateTableDefault(DbSyncCreationOption.CreateOrUseExisting);
config.Apply();
}
}
private static void prepareClinet(SqlSyncProvider provider, SqlConnection sourceConnection)
{
SqlConnection connection = (SqlConnection)provider.Connection;
SqlSyncScopeProvisioning config = new SqlSyncScopeProvisioning(connection);
if (!config.ScopeExists(provider.ScopeName))
{
DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(provider.ScopeName);
scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Author_Master", sourceConnection));
config.PopulateFromScopeDescription(scopeDesc);
config.Apply();
}
}
}
}
You can enable sync framework tracing in verbose mode to trace the synchronization. Likewise, did you forget to set the sync direction?