Export CSV file to FTP site using SQL - sql-server

Does anyone know how to export CSV file to FTP site in SQL management studio?
I am currently using
exec xp_cmdshell 'net use \ftp://213.32.32 \user:fjdowj ddfdf'
But it doesn't work at all
Thanks

you can try CLR stored procedure to generate CSV file and export to FTP site.
Generating CSV file to a path is given below:
public static void GenerateCSVFile(SqlString queryToGetData, SqlString folderPath)
{
string sqlCommand;
string filePath;
try
{
sqlCommand = queryToGetData.ToString();
filePath = folderPath.ToString() + "\\GeneratedFile" + ".csv";
using (SqlConnection connection = new SqlConnection(
"context connection=true"))
{
connection.Open();
SqlCommand command = new SqlCommand(sqlCommand,connection);
using (SqlDataReader reader = command.ExecuteReader())
{
DataTable table = new DataTable();
table.Load(reader);
StringBuilder builder = new StringBuilder();
List<string> columnNames = new List<string>();
List<string> rows = new List<string>();
foreach (DataColumn column in table.Columns)
{
columnNames.Add(column.ColumnName);
}
builder.Append(string.Join(",", columnNames.ToArray())).Append("\n");
foreach (DataRow row in table.Rows)
{
List<string> currentRow = new List<string>();
foreach (DataColumn column in table.Columns)
{
object item = row[column];
currentRow.Add(item.ToString());
}
rows.Add(string.Join(",", currentRow.ToArray()));
}
builder.Append(string.Join("\n", rows.ToArray()));
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.Write(builder.ToString());
}
}
}
}
catch(Exception ex)
{
throw;
}
}
Once you generate file, you can use the below approach to load to FTP path.
FTP Directly in SQL

xp_cmdshell is disabled by default (for very good reasons) on all recent versions of SQL Server. You could re-enable it manually (and I encourage you NOT to), but then you'd need an ftp command line tool to do the upload-- I don't think that net use command is going to do the trick. If you did manage to map an ftp end point as a drive with net use as the SQL Server service user, you would still need to achieve copying the file from SSMS to the filesystem on the server before running the FTP job.

Related

Reading from CosmosDB and write to Azure SQL

I have an Azure function to read from Cosmos DB and write to SQL. Since I am new to coding I have a little of struggle to understand how to read the incoming document. I can see that documents are shown at input:
public static async Task Run([CosmosDBTrigger(
databaseName: "ToDoList",
collectionName: "Items",
ConnectionStringSetting = "CosmosDB",
LeaseCollectionName = "leases")]IReadOnlyList<Document> input, ILogger log)
{
if (input != null && input.Count > 0)
{ }
I know that I have to read the document and deserialise it to a C# object which I have this code for (assuming it is correct):
Record resultRecord = JsonConvert.DeserializeObject<Record>(jsonString);
I am lost how to get the data from the json document and write it to the C# object. The connecting part is confusing for me.
I also have a SQL code, and again I dont understand how I should connect my C# object so the data can be read and written to SQL database.
var cnnString = "sqlConnection"; // Connecting to Azure SQL Database
using (var sqlConnection = new SqlConnection(cnnString)) // Start up sql connectin with connectionstring
{
sqlConnection.Open();
var cmd = new SqlCommand
{
//Insert into command (used to insert data into a table)
CommandText = #"insert into [dbo].[Player] ([User] values(#User)",
CommandType = CommandType.Text,
Connection = sqlConnection,
};
var record = new Record();
//set parameters
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#User", record.Email));
await cmd.ExecuteNonQueryAsync();
I am not sure if this is the right way of asking a question about a code, but I appreciate any help.
You want to get data from a json document,we can use the Newtonsoft.Json.dll file to parse the json document.
I think you can change you code like this:
List<Info> jobInfoList = JsonConvert.DeserializeObject<List<Info>>(json);
And here is a sample about how to get data from a json documnet:
class Program
{
static void Main(string[] args)
{
string json = #"[{'id':9527,'username':'admin'}]";
List<Info> jobInfoList = JsonConvert.DeserializeObject<List<Info>>(json);
foreach (Info jobInfo in jobInfoList)
{
Console.WriteLine("UserName:" + jobInfo.username);
}
}
}
public class Info
{
public string id { get; set; }
public string username { get; set; }
}
You can declare variables to receive the data which you want to get from the json String in foreach . Then you can insert these data into your sql database as the parameters.
How to connect to the sql database and write data to sql database,you can see:
Quickstart:
Use .NET (C#) with Visual Studio to connect and query an Azure SQL database
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-dotnet-visual-studio#insert-code-to-query-sql-database

Using a SQL Server mdf file easy on any Windows without any authentication

I have a SQL Server .MDF database file that contains data and tables that I need to load into my project and add or update that data so when I attach the file and run my program on a second PC that has SQL Server already installed, I get error that database is not found!
Note1: database was created in SQL Server 2012 local host server and Windows authentication mode.
I am using this code for loading and using database :
SqlConnection c = new SqlConnection(#"Data Source=.;Initial Catalog=db1;Integrated Security=True");
private void Form1_Load(object sender, EventArgs e)
{
String str;
SqlConnection myConn = new SqlConnection(#"Data Source=.;Initial Catalog=db1;Integrated Security=True");
str = "CREATE DATABASE db1";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("First db is Created", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
// MessageBox.Show("DB is exist");
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
using (SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=db1;Integrated Security=True"))
{
try
{
//Open.the SqlConnection;
con.Open();
//The following code uses a SqlCommand based on the SqlConnection
using (SqlCommand command = new SqlCommand("CREATE TABLE contents(id int IDENTITY(100, 1),Name char(50) NOT NULL,Lastname char(50) NOT NULL,Number char(50) ,Area nvarchar(50) ,Date nvarchar(50)NULL,Duration nvarchar(MAX),description nvarchar(MAX),gender nvarchar(50),number2 nvarchar(50),DT datetime NULL);", con))
command.ExecuteNonQuery();
}
catch (Exception ex)
{
//MessageBox.Show("Tables created");
}
}
}
Load table
private void button4_Click(object sender, EventArgs e)
{
SqlDataAdapter a = new SqlDataAdapter("select * from contents", c);
DataTable t = new DataTable();
a.Fill(t);
dataGridView1.DataSource = t;
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount - 1;
dataGridView1.AutoResizeColumns();
}
But it's not very unique and useful the db will be moved every day to another PC and it must load perfectly also I have some table in SQL file that are static and their is no need to code for them, I want to just use them as resource. Also I heard about some method that embedded or local db can be used as db in app data folder and can be moved with app wisely so I need some help here. Thanks
instead of creating a raw db everytime, you can use your mdf file as source,like below
Create database dbname
On
(
Filename= 'path where you copied mdf file'
)
For attach;

Change Connection String in App.config at runtime

The code below serves to change connection string in App.config at runtime, I found it here but this code did not work for me on Visual Studio 2010 and SQL Server 2008, I could not open the connection to the Northwind database.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace MyNameSpace
{
public partial class FrmConnectionTest : Form
{
public FrmConnectionTest()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//Constructing connection string from the inputs
StringBuilder Con = new StringBuilder("Data Source=");
Con.Append(TxtServer.Text);
Con.Append(";Initial Catalog=");
Con.Append(TxtDatabase.Text);
Con.Append(";Integrated Security=SSPI;");
string strCon = Con.ToString();
updateConfigFile(strCon);
//Create new sql connection
SqlConnection Db = new SqlConnection();
//to refresh connection string each time else it will use previous connection string
ConfigurationManager.RefreshSection("connectionStrings");
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
//To check new connection string is working or not
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
DataTable dt = new DataTable();
da.Fill(dt);
CmbTestValue.DataSource = dt;
CmbTestValue.DisplayMember = "EmployeeID";
}
catch (Exception E)
{
MessageBox.Show(ConfigurationManager.ConnectionStrings["con"].ToString() + ".This is invalid connection", "Incorrect server/Database");
}
}
public void updateConfigFile(string con)
{
//updating config file
XmlDocument XmlDoc = new XmlDocument();
//Loading the Config file
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "connectionStrings")
{
//setting the coonection string
xElement.FirstChild.Attributes[2].Value = con;
}
}
//writing the connection string in config file
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
}
Using Visual Studio 2010 and SQL Server2008, I got 2 errors for the next line:
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
Error 1 The best overloaded method match for 'System.Data.SqlClient.SqlDataAdapter.SqlDataAdapter(System.Data.SqlClient.SqlCommand)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'string' to 'System.Data.SqlClient.SqlCommand'
Is there any solution to this issue? Thank you.
The error is telling you that you are passing incorrect parameters to your SqlDataAdapter. I think the proper call would be:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
Edit
It looks like you're creating your connection string from within your program, saving it to your config file, then reading it out of our config file right before you create your SqlDataAdapter. So, when you debug this line:
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
Double check that Db.ConnectionString actually contains a connection string.
The other thing to do is open up your SQL Server Management Studio and confirm you can connect to the Northwind database from there. Including/alternatively, in Visual Studio, open your "Server Explorer" window and confirm you can create a Data Connection to Northwind by clicking Add Connection and then setting the connection property window to your server and dropping down the combobox to see if it populates with your databases:
Take a look at the available constructors of the SqlDataAdapter class.
There is no constructor overload that accepts just an SQL String.
You need to use one of the other overloads.
For example, there is one that needs an SQL String and a SqlConnection object.
To use it, change your code like this:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
EDIT:
As BradRem already mentioned in his comment, try a different connection string.
If his example doesn't work for you, you can find more possible examples at http://connectionstrings.com/sql-server-2008.
Do you really have a database called Northwind on your server?
Does the Windows user on your current machine have permissions on the server to access the database? (that's what Integrated Security=SSPI means - your current Windows user is used to access the database!)

How can I get SQL Server database properties from C# code?

I've a C# 4.0 console application and a SQL Server 2008 database up and running on database server.
Does somebody know if there is a way to get the database properties (like "Database Read-Only" ) from the C# code?
My guess is it should be, but I was not able to find out the accurate solution.
Thanks in advance
There are at least two ways to do it. One is to use the Database Metadata tables the other to use SQL Management objects in both cases there's lot of data there so you really need to know what you want. For example this is how you would get the "Database Read-Only" property you mentioned.
Using a SqlCommand against the MetaData
using (SqlConnection cnn = new SqlConnection("Data Source=.;Initial Catalog=master;Integrated Security=SSPI;"))
{
SqlCommand cmd = new SqlCommand("SELECT is_read_only FROM sys.filegroups",cnn);
cnn.Open();
var isReadOnly = cmd.ExecuteScalar();
Console.WriteLine(isReadOnly );
}
Using SMO
using System;
using Microsoft.SqlServer.Management.Smo;
namespace SMO_Test
{
class Program
{
static void Main(string[] args)
{
Server srv = new Server(); //Connection to the local SQL Server
Database db = srv.Databases["master"];
foreach (FileGroup fg in db.FileGroups)
{
Console.WriteLine(fg.ReadOnly);
}
}
}
}

Can we connect Sharepoint to SQL Server 6.5?

Not able to import application definition file!! Error: The metadata object with Name 'XYZ' and of Type 'LobSystemInstance' has a Property with Name 'DatabaseAccessProvider' that has either an invalid value or Type. Error was encountered at or just before Line: '10' and Position: '10'.
line 10 in ADF:
<"Property Name="DatabaseAccessProvider" Type="System.String">SqlOledb<"/Property>
Please give me ideas on how to display data from SQL Server 6.5 in Sharepoint?
The value of the node is invalid. You need to use SqlServer or OleDb. Check out this page for more information:
http://msdn.microsoft.com/en-us/library/ms550725(office.12).aspx
Im just starting on a similar task (so I found your unanswered question). I am trying to copy our documentation library in Sharepoint to an SQL db. Its not opening your file directly from SQL its using some c# code to setup a job which opens the sharepoint which may be what you are wanting.
There are two methods I have found so far:
One is to copy your data from sharepoint to a linked list in Access and then use the OLEDB methods in to open it.
Found here: C# Sync MS Access database to sql server
private static void BulkCopyAccessToSQLServer
(CommandType commandType, string sql, string destinationTable)
{
string connectionString = #"C:\Migration\Sharepoint Access SQL Batch Job\Database11.accdb";
using (DataTable dt = new DataTable())
{
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Migration\Sharepoint Access SQL Batch Job\Database11.accdb;Jet OLEDB:Database Password=password";
//using (OleDbConnection conn = new OleDbConnection(Settings.Default.CurriculumConnectionString))
using (OleDbConnection conn = new OleDbConnection(ConnStr))
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
cmd.CommandType = commandType;
cmd.Connection.Open();
adapter.SelectCommand.CommandTimeout = 240;
adapter.Fill(dt);
adapter.Dispose();
}
using (SqlConnection conn2 = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))
using (SqlConnection conn2 = new SqlConnection(connectionString))
{
conn2.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(conn2))
{
copy.DestinationTableName = destinationTable;
copy.BatchSize = 1000;
copy.BulkCopyTimeout = 240;
copy.WriteToServer(dt);
copy.NotifyAfter = 1000;
}
}
}
}
The other is to use the Microsoft.Sharepoint libraries and open your sharepoint directly from the c# then copy it into your SQL.
Found here: http://www.dotnetspark.com/kb/3573-fetching-lists-from-sharepoint-2010-site.aspx
using (SharePointclientObj.ClientContext ctx = new SharePointclientObj.ClientContext(clientContext))
{
//Get the site
SharePointclientObj.Web site = ctx.Web;
ctx.Load(site);
//Get Lists
ctx.Load(site.Lists);
//Query
ctx.ExecuteQuery();
//Fill List
foreach (SharePointclientObj.List list in site.Lists)
{
Console.WriteLine(list.Title);
}
}

Resources