My following code has two problems.
1- It doesn't go to the next row in dataset (when I run it, it just run firefox for 2916 times). I change this it from
var test = url.Replace("<userid>", Convert.ToString(row[userID]));
to
var test = url.Replace("<userid>", Convert.ToString(row["userID"]));
but it shows an error (Column 'userid' does not belong to table).
2- I want to close the firefox webpage page at the end of each loop and for next loop it runs again(because of performance issue)
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.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the userID
adapter.Fill(dt);
int userid=0,trackid=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row[userid]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/userid?groups=userid");
if (client.ToLower() == (Convert.ToString(trackid).ToLower()))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average = " + counter);
}
conn.Close();
}
}
}
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["userid"])); // You need ""
System.Diagnostics.Process.Start(test); // You should use variable test, which contains your url with <userid> replaced.
Related
Ths code as it appears works fine but here i insert by Add. all the values into the listTables. While what I want is to assing an object variable (User::Hosps) from SSIS (system.object) to the list (or to an array)
How can it be done?
This part:
OleDbDataAdapter A = new OleDbDataAdapter();
System.Data.DataTable dt = new System.Data.DataTable();
A.Fill(dt, Dts.Variables["User::Hosps"].Value);
is something i found online and tryed to use but the values it assigns to the list are not the values i want from the object.
#region Namespaces
using System;
using System.Data;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.OleDb;
using Microsoft.SqlServer.Dts.Runtime;
using System.Diagnostics;
using System.Collections.Generic;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
#endregion
namespace ST_ef6fc7b20ff94cbfb2587ed23a6520a0
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
OleDbDataAdapter A = new OleDbDataAdapter();
System.Data.DataTable dt = new System.Data.DataTable();
A.Fill(dt, Dts.Variables["User::Hosps"].Value);
foreach (DataRow row in dt.Rows)
{
Tables.Add(row.ToString());
}
List<string> Tables = new List<string>();
Tables.Add("ABRAVIV");
Tables.Add("FLIMANAVIV");
Tables.Add("BSHAVIV");
Tables.Add("LEVAVIV");
Tables.Add("BEERAVIV");
Tables.Add("TIRAAVIV");
Tables.Add("SHRAVIV");
Tables.Add("MAZAVIV");
Tables.Add("NTNYAAVIV");
Tables.Add("SHMUELAVIV");
Tables.Add("PARDESAVIV");
Tables.Add("RISHONAVIV");
Parallel.ForEach(Tables, Table =>
{
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = "Data Source=vmbi-devdb\\gp;Initial Catalog=GP;Integrated Security=True;Pooling=false;";
SqlDataReader rdr = null;
myConnection.Open();
SqlCommand cmd = new SqlCommand("exec Mirror_Logistic.Load_Table_From_Source " + Table, myConnection);
cmd.CommandTimeout = 0;
rdr = cmd.ExecuteReader();
myConnection.Close();
});
}
#region ScriptResults declaration
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Actually the variable User::Hosps contains the same values i assigned with the Tables.Add
Sorry, you got me confused.
Do you want to assign the values from ur SSIS-Object to a list?
Or do you want to assign ur values from C# to your object?
public void Main()
{
OleDbDataAdapter A = new OleDbDataAdapter();
System.Data.DataTable dt = new System.Data.DataTable();
A.Fill(dt, Dts.Variables["User::Hosps"].Value); List<string> myValues = new list<string>();
foreach (DataRow row in dt.Rows)
{
myValues.Add(row[0].ToString());
}
I have a .csv file and I'd like to read it into a datagridview (each value into an each column).
I read this file with block note and I see that each value is divided by ";"
I tried to set a datatable but it's not working. This is my code:
string FileName = #"C:\mydir\testcsv.csv";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + Path.GetDirectoryName(FileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + Path.GetFileName(FileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
conn.Close();
dataGridView2.DataSource = ds;
I don't understand where's the error.
Your code worked for me as it is.
I just added one line to the datasource assignment after looking inside the dataset, I saw just one table is inside with name "Table" so I assigned the datamember of the datagridview:
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Table";
Anyway if I used ';' separator, all the values were in one column... With ',' comma separator it works ok.
The complete code of the form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string FileName = #"C:\mydir\testcsv.csv";
OleDbConnection conn = new OleDbConnection
("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +
Path.GetDirectoryName(FileName) +
"; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter
("SELECT * FROM " + Path.GetFileName(FileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
conn.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Table";
}
}
}
Contents of the csv file:
abc,123
def,456
ijk,789
lmn,111213
For semicolon delimited files you need to add an ini file in your folder containing the csv file. How to do it exactly is described here:
How to specify the delimiter when importing CSV files via OLEDB in C#
For decimal delimiter symbol you have to add the
DecimalSymbol
directive to your Jet ini file.
See the full ini file capabilities documented in MSDN (https://msdn.microsoft.com/en-us/library/ms709353(v=vs.85).aspx)
I use this function by long, long time, after: yourgrid.datasource = function result.
public static DataTable CsvDb(string filename, string separatorChar)
{
var table = new DataTable("Filecsv");
using (var sr = new StreamReader(filename, Encoding.Default))
{
string line;
var i = 0;
while (sr.Peek() >= 0)
{
try
{
line = sr.ReadLine();
if (string.IsNullOrEmpty(line)) continue;
var values = line.Split(new[] { separatorChar }, StringSplitOptions.None);
var row = table.NewRow();
for (var colNum = 0; colNum < values.Length; colNum++)
{
var value = values[colNum];
if (i == 0)
{
table.Columns.Add(value, typeof(String));
}
else
{ row[table.Columns[colNum]] = value; }
}
if (i != 0) table.Rows.Add(row);
}
catch (Exception ex)
{
string cErr = ex.Message;
//if you need the message error
}
i++;
}
}
return table;
}
Try...
I got the error message below when I tried to upload a csv file to a SQL Server table using C# (csv file has no header).
Error Message : "A column named ' ' already belongs to this DataTable"
I tried to find some solutions somewhere on the web but I'm really stuck with it.
My code :
SqlConnection con = new SqlConnection(#"server=.;Initial Catalog=myDtabase;Integrated Security=SSPI;");
string filepath = #"c:\\my_CSV_file.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "my_SQLServer_Table";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
I think this link will help you get this done.
http://forums.asp.net/t/1695615.aspx
As usual, there is more than one way to skin a cat. So, if yo don't like the solution listed above, try this script, which I know will work for you.
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.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string server = "EXCEL-PC\\EXCELDEVELOPER";
string database = "AdventureWorksLT2012";
string SQLServerConnectionString = String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI", server, database);
string CSVpath = #"C:\Users\Ryan\Documents\Visual Studio 2010\Projects\Bulk Copy from CSV to SQL Server Table\WindowsFormsApplication1\bin"; // CSV file Path
string CSVFileConnectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};;Extended Properties=\"text;HDR=Yes;FMT=Delimited\";", CSVpath);
var AllFiles = new DirectoryInfo(CSVpath).GetFiles("*.CSV");
string File_Name = string.Empty;
foreach (var file in AllFiles)
{
try
{
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(CSVFileConnectionString))
{
con.Open();
var csvQuery = string.Format("select * from [{0}]", file.Name);
using (OleDbDataAdapter da = new OleDbDataAdapter(csvQuery, con))
{
da.Fill(dt);
}
}
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(SQLServerConnectionString))
{
bulkCopy.ColumnMappings.Add(0, "MyGroup");
bulkCopy.ColumnMappings.Add(1, "ID");
bulkCopy.ColumnMappings.Add(2, "Name");
bulkCopy.ColumnMappings.Add(3, "Address");
bulkCopy.ColumnMappings.Add(4, "Country");
bulkCopy.DestinationTableName = "AllEmployees";
bulkCopy.BatchSize = 0;
bulkCopy.WriteToServer(dt);
bulkCopy.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
}
The CsvHelper NuGet library has an implementation for IDataReader which you can pass into the BulkCopy WriteToServer method. This makes for really simple code and allows you to customize the data import.
using CsvHelper;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System.Globalization;
using System.IO;
public int ReplaceTableWithFile(string table, FileInfo csvFile)
{
using var fileReader = new StreamReader(csvFile.OpenRead());
using var csv = new CsvReader(fileReader, CultureInfo.InvariantCulture);
using var csvDataReader = new CsvDataReader(csv);
var connection = GetDbConnection();
using var command = new SqlBulkCopy(connection);
command.EnableStreaming = true;
command.DestinationTableName = table;
command.WriteToServer(csvDataReader);
return command.RowsCopied;
}
CsvDataReader from CsvHelper NuGet package
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
public class StockMainDL
{
string conString = "Data Source=KamranAhmed\\SQLEXPRESS;Initial Catalog=City_Car;Integrated Security=True";
SqlConnection con;
SqlCommand com;
SqlDataAdapter da;
DataSet ds;
public StockMainDL()
{
con = new SqlConnection(conString);
con.Open();
}
public List<StockMain> GetChartData(string mode)
{
List<StockMain> stockMain = new List<StockMain>();
string query = "SELECT * FROM StockMain";
com = new SqlCommand(query);
da = new SqlDataAdapter(query, con);
da.Fill(ds);
foreach (DataRow item in ds.Tables[0].Rows)
{
stockMain.Add(new StockMain(Int32.Parse(item["Stid"]), Int32.Parse(item["Vrno"]), Int32.Parse(item["Vrnoa"]), Convert.ToDateTime(item["Vrdate"]), item["Party_id"].ToString(), item["Bilty_No"].ToString(), Convert.ToDateTime(item["Bilty_Date"]), item["Received_By"].ToString(), item["Transporter_id"].ToString(), item["Remarks"].ToString(), Int32.Parse(item["Year_Srno"]), item["EType"].ToString(), Int32.Parse(item["NAmount"]), Int32.Parse(item["UId"]), Int32.Parse(item["VrNo"]), Int32.Parse(item["OrderVrNo"]), Int32.Parse(item["Freight"]), item["Party_Id_Co"].ToString(), Int32.Parse(item["SaleBillNo"]), float Discp, float Discount, Int32.Parse(item["Currency_Id"]), float Expense, Int32.Parse(item["Company_Id"]), item["Vehicle_Id"].ToString(), Convert.ToBoolean(Item["IsEditted"]), Convert.ToBoolean(Item["IsNew"]), Convert.ToBoolean(Item["IsDeleted"])));
}
return stockMain;
}
}
Above is the code that I'm using to first get the dataset from the database and the transform this dataset to a List and then return this list. The problem I'm having is, inside the foreach loop it gives this error "Cannot use 'Int32' before it is declared", I tried to use Convert.ToInt32() it gives the same error for "Convert".
Can anybody please tell me what I'm doing wrong?
Thanks
you are using Item instead of item inside that FOR loop for few parameters. That is throwing you this error. Remember the variables used are case-sensitive
I have been trying to figure this out for hours now, I know there is some small error that I have here but I am not able to pinpoint it. Please help me.
So I created a class called "clsDataLayer.cs" and it is in the App_Code asp.net folder.
I then created a form called "frmUserActivity", but now when I post the code in it and call the class it says "The "clsDataLayer" does not exists in current context" Can anyone please help me?
code for clsDataLayer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// Add your comments here
using System.Data.OleDb;
using System.Net;
using System.Data;
namespace ASP_PayRoll.App_Code
{
public class clsDataLayer
{
// This function gets the user activity from the tblUserActivity
public static dsUserActivity GetUserActivity(string Database)
{
// Add your comments here
dsUserActivity DS;
OleDbConnection sqlConn;
OleDbDataAdapter sqlDA;
// Add your comments here
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
// Add your comments here
sqlDA = new OleDbDataAdapter("select * from tblUserActivity", sqlConn);
// Add your comments here
DS = new dsUserActivity();
// Add your comments here
sqlDA.Fill(DS.tblUserActivity);
// Add your comments here
return DS;
}
// This function saves the user activity
public static void SaveUserActivity(string Database, string FormAccessed)
{
// Add your comments here
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
strSQL = "Insert into tblUserActivity (UserIP, FormAccessed) values ('" +
GetIP4Address() + "', '" + FormAccessed + "')";
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
command.ExecuteNonQuery();
conn.Close();
}
// This function gets the IP Address
public static string GetIP4Address()
{
string IP4Address = string.Empty;
foreach (IPAddress IPA in
Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != string.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
}
}
Code for frmUserActivity.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASP_PayRoll
{
public partial class frmUserActivity : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Declare the DataSet
dsUserActivity myDataSet = new dsUserActivity();
//Fill the dataset with what is returned from the function
myDataSet = clsDataLayer.GetUserActivity(Server.MapPath("PayrollSystem_DB.mdb"));
//Sets the DataGrip to the DataSource based on the table
grdUserActivity.DataSource = myDataSet.Tables["tblUserActivity"];
//Binds the DataGrid
grdUserActivity.DataBind();
}
}
}
}
Thanks in advance.
Ak
Use ASP_PayRoll.App_Code.clsDataLayer. Your namespace in your data layer class is ASP_PayRoll.App_Code and in your page it's ASP_PayRoll.
Add using ASP_PayRoll.App_Code; to your aspx file.
Since you declared that in a namespace other than the one of your aspx page, you have to use a using statement, or the entire path (ASP_PayRoll.App_Code.clsDataLayer) in order to be able to access that class.