I am connecting to a SharePoint list using the following code. The problem is that if I run a Command, the console application hangs and doesn't close. I can see that the application is still consuming memory. Without a Command, the debugger exits cleanly.
I am also looking for a way to connect to SharePoint with EntityFramework, or a more modern way that doesn't use the SharePoint API.
The sample uses several methods to connect to the same SharePoint list.
namespace TestADO
{
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using ADODB;
internal class Program
{
public static string ConnectionStringBase = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=2;RetrieveIds=Yes;Pooling=false;DATABASE=https://.../sites/...;LIST={xxxxxxx-ac0a-4cb3-8a32-ecbdxxxxxxxx}";
public static string sql = "select top 10 * from [Call Distributions]";
static void Main(string[] args)
{
ADONetImplementationWithAdapter();
ADONetImplementation();
}
static void ADONetImplementationWithAdapter()
{
OleDbDataAdapter oledbAdapter;
using (OleDbConnection conn = new OleDbConnection(ConnectionStringBase))
{
DataSet ds = new DataSet();
conn.Open();
oledbAdapter = new OleDbDataAdapter(sql, conn);
oledbAdapter.Fill(ds);
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
Console.WriteLine(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
oledbAdapter.Dispose();
conn.Close();
}
}
static void ADONetImplementation()
{
using (OleDbConnection conn = new OleDbConnection(ConnectionStringBase))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
var reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetValue(0) + " - " + reader.GetValue(1) + " - " + reader.GetValue(2));
}
reader.Close();
cmd.Dispose();
}
conn.Close();
}
}
static void ADOImplementation()
{
Connection connection = new Connection();
connection.CursorLocation = CursorLocationEnum.adUseServer;
connection.ConnectionString = ConnectionStringBase;
connection.Open();
object res;
var rst = connection.Execute(sql, out res);
while (!rst.EOF)
{
rst.MoveNext();
}
rst.Close();
rst = null;
//Recordset recordset = new Recordset();
//recordset.Open(sql, connection, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockOptimistic);
//recordset.Close();
//recordset = null;
connection.Close();
connection = null;
}
}
}
Please try to use the following code to connect to SharePoint:
using Microsoft.SharePoint.Client;
using System;
using System.Linq;
using System.Security;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string siteCollectionUrl = "https://globalsharepoint2020.sharepoint.com";
string userName = "YourSPOUserName#yourtenant.onmicrosoft.com";
string password = "YourSPOPassword";
Program obj = new Program();
try
{
obj.ConnectToSharePointOnline(siteCollectionUrl, userName, password);
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
}
}
public void ConnectToSharePointOnline(string siteCollUrl, string userName, string password)
{
//Namespace: It belongs to Microsoft.SharePoint.Client
ClientContext ctx = new ClientContext(siteCollUrl);
// Namespace: It belongs to System.Security
SecureString secureString = new SecureString();
password.ToList().ForEach(secureString.AppendChar);
// Namespace: It belongs to Microsoft.SharePoint.Client
ctx.Credentials = new SharePointOnlineCredentials(userName, secureString);
// Namespace: It belongs to Microsoft.SharePoint.Client
Site mySite = ctx.Site;
ctx.Load(mySite);
ctx.ExecuteQuery();
Console.WriteLine(mySite.Url.ToString());
}
}
}
Related
I'm trying to dynamically add rows from some excel files located in a directory to a OleDbDataAdapter.
So far,I managed to add some data to the OleDbDataAdapter by dynamically generating OleDbConnections that each point to the respective excel files from which i want to read data. However, the code stops after reading the first excel file. I suspect that I have to clear some variables but I'm kinda stuck for now.
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApp35
{
class Program
{
static void Main(string[] args)
{
string dirALC_EDC = #"C:\Users\________\Desktop\Mission\Fichiers\ALC_EDC\";
var files = Directory.GetFiles(dirALC_EDC, "*.*", SearchOption.AllDirectories);
foreach (string file in files)
{
String theConnString = (String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", file));
OleDbConnection excelConnection = new OleDbConnection(theConnString);
excelConnection.Open();
var dt = new DataTable();
var da = new OleDbDataAdapter();
var _command = new OleDbCommand();
_command.Connection = excelConnection;
_command.CommandText = "select * FROM [Sheet1$]";
da.SelectCommand = _command;
try
{
da.Fill(dt);
for (int i = 4; i <= dt.Rows.Count; i++)
{
Console.WriteLine(String.Join(", ", dt.Rows[i].ItemArray));
}
}
catch (Exception e)
{
// process error here
}
Console.ReadLine();
}
}
}
}
I'm building a desktop application where when a used logged it in new his Id will be appeared in textBox. But in my case query run successfully but id doesn't appear in textBox..can anyone help me to find it out please?
First form of User logged in (Form1.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
public string employeeID;
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void loginButton_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True");
connection.Open();
String query = "select * from Employees where Name = '" + nameTextBox.Text + " ' and Password = '" + passwordTextBox.Text + "'";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
string employeeID = myReader["EmployeeID"].ToString();
}
myReader.Close();
SqlDataAdapter sda = new SqlDataAdapter(query,connection);
connection.Close();
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count == 1)
{
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
}
}
}
Second form (Entry.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EmployeeApp
{
public partial class Entry : Form
{
public Entry()
{
InitializeComponent();
}
public Entry(string employeeId)
{
InitializeComponent();
idTextBox.Text = employeeId;
}
private void reportButton_Click(object sender, EventArgs e)
{
Report report = new Report();
report.Show();
}
}
}
Remove local variable declaration, because employeeID is a global variable and already declared first, so when you prefix it using string its create another local variable which is not accessible outside this scope
while (myReader.Read())
{
employeeID = myReader["EmployeeID"].ToString();
}
You have a local variable. You can correct and optimize you code like this:
private void loginButton_Click(object sender, EventArgs e)
{
//If use set quote into your textbox
string name = nameTextBox.Text.Replace("'", "''");
string pass = passwordTextBox.Text.Replace("'", "''");
String query = string.Format("select * from Employees where Name = '{0}' and Password = '{1}'", name, pass);
string employeeID = "";
using (SqlConnection connection = new SqlConnection(#"Data Source=INCEPSYS-SE\TEST;Initial Catalog=Employee;Integrated Security=True"))
{
connection.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(query, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
employeeID = dt.Rows[0]["EmployeeID"].ToString();
this.Hide();
Entry ss = new Entry(employeeID);
ss.Show();
}
else
{
MessageBox.Show("Please Check your Username & password");
}
dt.Dispose();
}
}
}
I am needing to take all of my access tables and create the exact same table in SQL Server 2008 with data and keys/constraints. The below syntax will insert data if the table already exists, but how do I do it if the table does not exist? Or is there a better method programmatic ally in play to already achieve this result?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AccessToSQL
{
public partial class Form1 : Form
{
const string databaselocation = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Database1.accdb;Persist Security Info = False;";
List<string> tables = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
GetTableNames();
const string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Database1.accdb;Persist Security Info = False;";
const string connectionStringDest = "Data Source = TO\\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=SSPI;";
using (var sourceConnection = new OleDbConnection(connectionString))
{
sourceConnection.Open();
using (var destinationConnection = new SqlConnection(connectionStringDest))
{
destinationConnection.Open();
foreach (string tbl in tables)
{
var commandSourceData = new OleDbCommand("Select * from "+tbl, sourceConnection);
var reader = commandSourceData.ExecuteReader();
using (var bulkCopy = new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName = "dbo."+tbl;
try { bulkCopy.WriteToServer(reader); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
finally { reader.Close(); }
}
}
}
}
}
public List<string> GetTableNames()
{
try {
using (OleDbConnection con = new OleDbConnection(databaselocation))
{
con.Open();
//DataTable schema = con.GetSchema("Columns");
//foreach (DataRow row in schema.Rows)
//{
// tables.Add(row.Field<string>("TABLE_NAME"));
//}
foreach (DataRow r in con.GetSchema("Tables").Select("TABLE_TYPE = 'TABLE'"))
{
tables.Add(r["TABLE_NAME"].ToString());
}
return tables;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
return tables;
}
}
}
I am messing around in C# trying to understand how to insert records into a database using C# ODBC. I have learned how to read in records to a DGV, but now I am getting stuck on inserting.
The quick overview of what my code is doing, its reading in 20 rows from a table into a DGV, then after that it should insert the same rows into a different table.
I am using VS 2012 and SQL Developer (Oracle).
Here is the code in my Form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication13
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (int rows = 0; rows < 20; rows++)
{
dataGridView1.Rows.Add(); // adding needed amount of rows
for (int cols = 0; cols < 13; cols++)
{
this.dataGridView1[cols, rows].Value = getNumberOfThreads(rows, cols);
}
}
StringBuilder sql = new StringBuilder();
sql.AppendLine("insert into chsarp_test_table");
sql.AppendLine("SELECT *");
sql.AppendLine("FROM legal_transactions");
sql.AppendLine("WHERE rownum between 1 and 25");
//using (DataTable dt = Database.GetData(sql.ToString()))
// if (dt.Rows.Count > 0)
// Database dt = new Database.SetData(sql.ToString());
Database.SetData(sql.ToString());
}
public static string getNumberOfThreads(int i, int j)
{
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT *");
sql.AppendLine("FROM legal_transactions");
sql.AppendLine("WHERE rownum between 1 and 25");
using (DataTable dt = Database.GetData(sql.ToString()))
if (dt.Rows.Count > 0)
return dt.Rows[i][j].Equals(DBNull.Value) ? "null" : dt.Rows[i][j].ToString();
return "null";
}
}
}
Here is the code from my Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Odbc; //used for the ODBC stuff
using System.Data; // Used for public static datatable
using System.Windows.Forms;
namespace WindowsFormsApplication13
{
class Database
{
private const string connOdbc = "dsn=atlas32;uid=NAME;pwd=XXXX";
private const string cnnOLE = "provider =XXXX;User ID = NAME;password = XXXX; Data Source = XXX Properties=;Persist Security Info=False";
public static DataTable GetData(string Sql)
{
DataTable dt = new DataTable();
try
{
OdbcConnection cnn = GetConnection();
using (OdbcDataAdapter da = new OdbcDataAdapter(Sql, cnn))
{
da.SelectCommand.CommandTimeout = 0;
da.Fill(dt);
}
CloseConnection(cnn);
}
catch (Exception ex)
{
//Queries.LogErrors(ex.Message, Sql);
MessageBox.Show("Error 1");
}
return dt;
}
public static void SetData(string sql)
{
try
{
OdbcConnection cnn = GetConnection();
using (OdbcCommand cmd = new OdbcCommand(sql, cnn))
cmd.ExecuteNonQuery();
CloseConnection(cnn);
}
catch (Exception ex)
{
//Queries.LogErrors(ex.Message, sql);
MessageBox.Show("Error 2");
}
}
private static OdbcConnection GetConnection()
{
try
{
OdbcConnection cnn = new OdbcConnection() { ConnectionString = connOdbc };
cnn.Open();
return cnn;
}
catch (Exception ex)
{
//throw ex;
}
return null;
}
private static void CloseConnection(OdbcConnection Connection)
{
try
{
if (Connection.State == ConnectionState.Open)
Connection.Close();
Connection.Dispose();
}
catch (Exception ex)
{
//throw ex;
}
Connection = null;
}
}
}
I tried to step through the code and it goes down in the SetData Method on the ExecuteNonQuery. I tried to look into this but couldnt mind any information that helped me, any push in the right direction would be greatly appreciated.
I was missing the Schema on the table I was inserting on. found this out with the help of #stuartd in the comment section of the question.
I am upgrading a asp website to asp.net. I am trying to follow multi teir approach.
My basic dal layer is as follows which returns a datatable and insert a given query.
using System;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;
public class mydatautility
{
public mydatautility()
{
}
public static DataTable Table(string query)
{
string constr = ConfigurationManager.ConnectionStrings["db_con"].ConnectionString;
DataTable table = new DataTable();
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
con.Close();
MySqlCommand com = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(com);
con.Open();
da.Fill(table);
con.Close();
da = null;
com = null;
con.Dispose();
}
}
catch (Exception)
{
}
return table;
}
public static int Insert_intoemployee(string query)
{
string constr = ConfigurationManager.ConnectionStrings["db_con"].ConnectionString;
int done = 0;
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
MySqlCommand com = new MySqlCommand(query, con);
con.Open();
done = com.ExecuteNonQuery();
con.Close();
com = null;
con.Dispose();
}
}
catch (Exception)
{
}
return done;
}
}
I am not sure what will happen when 2 concurrent queries are run.How can I test it for concurrency problem?
There will no concurrency problem as each request has its own thread and static methods have individual call stacks for each thread. However, there are some suggestions in code.
using System;
using System.Configuration;
using System.Data;
using MySql.Data.MySqlClient;
public static class mydatautility//change to Utilities
{
public mydatautility()//not required in this scenario
{
}
public static DataTable Table(string query) //change method name to GetTable
{
string constr = ConfigurationManager.ConnectionStrings["db_con"].ConnectionString;
DataTable table = new DataTable();
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
con.Close();//not required
using(MySqlCommand com = new MySqlCommand(query, con))
{
MySqlDataAdapter da = new MySqlDataAdapter(com);
con.Open();
da.Fill(table);
con.Close();
da = null;// reduntant, not required
com = null;// reduntant, not required
con.Dispose();// reduntant, not required
}
}
}
catch (Exception)
{
}
return table;
}
public static bool InsertEmployee(string query)// consider changing int to bool since you only require result of operation
{
string constr = ConfigurationManager.ConnectionStrings["db_con"].ConnectionString;
int done = 0;
try
{
using (MySqlConnection con = new MySqlConnection(constr))
{
Using(MySqlCommand com = new MySqlCommand(query, con))
{
con.Open();
done = com.ExecuteNonQuery();
con.Close();
com = null;// reduntant, not required
con.Dispose();// reduntant, not required
}
}
}
catch (Exception)
{
}
return done > 0; // checks rows affected greater than 0
}
}
Using static methods in this scenario is safe. The variables inside the static method is isolated from concurrent calls! see this link too: variable in static methods inside static class
I think it is safe, but bad practice. If you use static methods to access live resource, then how do you want to unit test them? You can not really mock the database access any more.