How to store Arabic language values from web-service in database - c#

I'm trying to store some Arabic values I got from a web service, but when I select them from the database and show them in a DataGridView it just shows "?????". The three columns in the database are nvarchar(50). How should I be storing them?
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.Xml;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string user = "gamal";
string p1 = "GAM123";
string p2 = "GAM123";
string sdate = "05152014000000";
string edate = "05182014235959";
string node = "232641";
string group = "Al Ahsa - ???????";
string Compress = "";
string m_d = "sa";
string lang = "1";
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
test_ws.ppppWebServiceSoapClient ws =
new test_ws.ppppWebServiceSoapClient("pppp Report Web ServiceSoap");
ds = ws.GetGroups(user, p1, p2);
DataSet ds_ra = new DataSet();
ds_ra = ws.RegionAlarm(user, p1, p2, sdate, edate, node, group, Compress, m_d, lang);
ds_ra.WriteXml("region_alarm.xml");
string connetionString = null;
SqlConnection connection;
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
string sql = null;
string ID = null;
string nodegroup = null;
string nodecount = null;
connetionString = #"Server=.\SQLEXPRESS; DataBase=hhhh; Integrated Security=True;";
connection = new SqlConnection(connetionString);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ID = ds.Tables[0].Rows[i].ItemArray[0].ToString();
nodegroup = ds.Tables[0].Rows[i].ItemArray[1].ToString();
nodecount = ds.Tables[0].Rows[i].ItemArray[2].ToString();
sql = "insert into groups (id,nodegroup,nodecount)
values(" + ID + ",'" + nodegroup + "'," + nodecount + ")";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
sql = "select * from groups";
command = new SqlCommand(sql, connection);
adpter.SelectCommand = command;
adpter.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
adpter.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
MessageBox.Show("Done ..تم ");
}
}
}

After ensuring the NodeGroup column in your table is an NVARCHAR(), use parameters instead of concatenation, for both preventing SQL injection, and to make sure your data types are properly set. When you were concatenating the sql, the string literal was a varchar, unless you put an N in front of the literal.
sql = "insert into groups (id,nodegroup,nodecount)
values(#ID,#NodeGroup, #NodeCount)";
command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#ID", id);
command.Parameters.AddWithValue("#NodeGroup", nodegroup);
command.Parameters.AddWithValue("#NodeCroup", nodecount);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();

Change this:
values(" + ID + ",'" + nodegroup + "'," + nodecount + ")";
into
values(" + ID + ", N'" + nodegroup + "'," + nodecount + ")";
However, you should really be using parameters instead of building an SQL string with the values in it. That will get you around all of the escaping issues.

When inserting in to database with inline sql you have to prefix the nvarchar value with 'N'. For example: insert into mytable (col1) values (N'myvalue')

Related

c# - MySQL to Array to MSSQL Query Statement

I'm working on a program to link two databases (MySQL and MSSQL) and show them in a datagrid table.
I'm getting a count to get the number of arrays value, then assigning the array, then using the array value to return into a datagrid table.
The problem I have is skuArray[RowCount++] = Convert.ToInt32(myReader[0]);is returning error: cannot convert int to string. I changed it to skuArray[RowCount++] = Convert.String(myReader[0]); and it complied correctly but gives the message Object reference not set to an instance of an object.
All SQL Queries have been tested and successfully execute.
Code:
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;
using MySql.Data.MySqlClient;
using System.IO;
using System.Xml.Serialization;
using System.Data.SqlClient;
namespace SQL_Database_Connector
{
public partial class Sync_Databases : Form
{
string serverInfo; // MySQL Database Information
string portInfo;
string databaseInfo;
string usernameInfo;
string passwordInfo;
string MSserverInfo; // MSSQL Database Information
string MSdatabaseInfo;
string MSusernameInfo;
string MSpasswordInfo;
public string[] skuArray;
public string queryString;
public int RowCount;
public Sync_Databases()
{
InitializeComponent();
}
private void Sync_Databases_Load(object sender, EventArgs e)
{
if (File.Exists("data.xml")) // MySQL Database
{
XmlSerializer xs = new XmlSerializer(typeof(Information));
FileStream read = new FileStream("data.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
Information info = (Information)xs.Deserialize(read);
serverInfo = info.server;
portInfo = info.port;
databaseInfo = info.database;
usernameInfo = info.username;
passwordInfo = info.password;
read.Close();
}
try
{
string MyConnection = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", serverInfo, portInfo, databaseInfo, usernameInfo, passwordInfo);
string Query = "SELECT COUNT(*) " +
"FROM catalog_product_entity " +
"INNER JOIN catalog_product_entity_int " +
"ON catalog_product_entity_int.entity_id = catalog_product_entity.entity_id " +
"WHERE catalog_product_entity.sku IS NOT NULL " +
"AND catalog_product_entity.sku <> 0 " +
"AND(catalog_product_entity_int.attribute_id = '84' AND catalog_product_entity_int.value = '1');";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
MyConn.Open();
MySqlDataReader myReader;
myReader = MyCommand.ExecuteReader();
try
{
while (myReader.Read())
{
RowCount = myReader.GetInt32(0); // Get Row Count
//MessageBox.Show(RowCount.ToString()); // Test Row Count
}
}
finally
{
myReader.Close();
MyConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Problem with Row Count: "+ ex.Message);
}
try
{
string MyConnection = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", serverInfo, portInfo, databaseInfo, usernameInfo, passwordInfo);
string Query = "SELECT catalog_product_entity.sku AS 'SKU' " +
"FROM catalog_product_entity " +
"INNER JOIN catalog_product_entity_int " +
"ON catalog_product_entity_int.entity_id = catalog_product_entity.entity_id " +
"WHERE catalog_product_entity.sku IS NOT NULL " +
"AND catalog_product_entity.sku <> 0 " +
"AND(catalog_product_entity_int.attribute_id = '84' AND catalog_product_entity_int.value = '1');";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
MyConn.Open();
MySqlDataReader myReader;
myReader = MyCommand.ExecuteReader();
try
{
while (myReader.Read())
{
skuArray[RowCount++] = Convert.ToString(myReader[0]); // Assigning Array Values
//MessageBox.Show(skuArray.ToString()); //T est
}
}
finally
{
myReader.Close();
MyConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Problem with MySQL query to capture Array: "+ ex.Message);
}
if (File.Exists("data2.xml")) // MSSQL Database
{
XmlSerializer xs = new XmlSerializer(typeof(Information));
FileStream read = new FileStream("data2.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
Information info = (Information)xs.Deserialize(read);
MSserverInfo = info.server;
MSdatabaseInfo = info.database;
MSusernameInfo = info.username;
MSpasswordInfo = info.password;
read.Close();
}
try
{
string connectionString = string.Format("Data Source={0}; Initial Catalog={1}; User ID={2}; Password={3};", MSserverInfo, MSdatabaseInfo, MSusernameInfo, MSpasswordInfo);
string sql = string.Format("SELECT ItemLookupCode,Description, Quantity, Price, LastReceived " +
"FROM Item " +
"WHERE ItemLookupCode IS IN {0} " +
"ORDER BY LastReceived ASC;", skuArray);
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "sql_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "sql_table";
SqlConnection conn = new SqlConnection();
}
catch (Exception ex)
{
MessageBox.Show("Problem with SQL query or connection: "+ ex.Message);
}
}
}
}
Where have you initialised the array?
I dont see any line which would say:
skuArray = new string[RowCount];
RowCount is just a placeholder i am using.

reading one record from access in C#

My requirement is to read Date column from access file and use one value to append it to a file name, so as to create file with date timestamp using the db value.
I am trying following approach but it gives me exception "No data exists for the row/column":
here's the code
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbConnection conn1 = new OleDbConnection(connectionString);
string dt = "SELECT top 1 Date FROM Events";
OleDbCommand cmd1 = new OleDbCommand(dt, conn1);
conn1.Open();
OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = rdr.GetInt32(0).ToString();
rdr.Close();
conn1.Close();
string path = text_dir + "\\" + time_stmp + "_" + "BWC_Ejournal.txt";
You'll need to call the Read() method on the OleDbDataReader object before accessing its data.
E.g.
OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = "";
if(rdr.Read())
{
time_stmp = rdr.GetInt32(0).ToString();
}
else
{
//handle no data situation here
}
This will also allow to handle a situation where no data is returned more gracefully too.
DATE is a reserved word in ACE/Jet SQL. Try this instead:
string dt = "SELECT TOP 1 [Date] FROM Events";
Edit
On taking a closer look at your code I notice that you create the OleDbCommand object before the connection is opened. I've seen that cause problems as well. FWIW, the following code works for me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace oleDbTest
{
class Program
{
static void Main(string[] args)
{
using (var con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\main.accdb;"))
{
con.Open();
using (var cmd = new OleDbCommand(
"SELECT TOP 1 [Date] FROM [Events]", con))
{
string time_stmp = Convert.ToDateTime(cmd.ExecuteScalar()).ToString("yyyyMMdd");
Console.WriteLine(time_stmp.ToString());
}
con.Close();
}
Console.WriteLine("Done.");
System.Threading.Thread.Sleep(2000);
}
}
}

custom query for datagridview

I am currently building an application in C#. In this application, people give values in a label and ​​that values will be saved in a database. This also works at the moment. What I want is the following:
The people can see their own values back in a datagridview. If I do this with the wizard of the datagridview I can't select label2.Text(this is the customerID).
The query I used below is the following:
SELECT * FROM prestaties WHERE gebruikerid = '" + label1.Text + "'";
But it doesn't work. I don't see anything in my datagrid.
Sorry for my bad English. I hope you can understand me.
The code below I already have, but it doesn't work
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;
namespace Eindopdracht
{
public partial class resultaten : Form
{
public resultaten()
{
InitializeComponent();
dataGridView1.Show();
}
private string username;
public void displaydata(String ddata)
{
OleDbConnection conn = new OleDbConnection(#"provider= microsoft.jet.oledb.4.0;data source=C:\\Users\\Jeffrey\\Desktop\\Eindopdracht WOE\\Eindopdracht\\sample.mdb");
string select = "SELECT * FROM prestaties WHERE gebruikerid = '" + label2.Text + "'";
conn.Open();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(select, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.DataSource = ds.tables[0];
conn.Close();
}
public void setUsername(String name)
{
username = name;
label1.Text = username;
setID();
}
public void setID()
{
OleDbConnection vcon = new OleDbConnection(#"provider= microsoft.jet.oledb.4.0;data source=C:\\Users\\Jeffrey\\Desktop\\Eindopdracht WOE\\Eindopdracht\\sample.mdb");
string selectie = "SELECT id FROM inlog WHERE Username='" + label1.Text + "'";
OleDbCommand vcom1 = new OleDbCommand(selectie, vcon);
vcon.Open();
vcom1.ExecuteNonQuery();
OleDbDataReader dr = null;
dr = vcom1.ExecuteReader();
while (dr.Read())
{
var waarde = dr.GetValue(0);
label2.Text = waarde.ToString();
}
I don't know if my code is 100% correct. I've build this by myself. If I use the class displayData in the begin next to InitializeComponent(); I will get an error.

Programmatically acess Google chrome history

I want to index all the user actions and websites in google chrome. i understand that google chrome index all the data in sqlLite database. how can i Programmatically access the chrome web history in my own application
You need to download the appropriate assembly from the SqLite downloads page
Once you add a reference to the SQLite assembly, its very similar to standard ADO.net
All the user history is stored in the History database located at the path in the connection string below
SQLiteConnection conn = new SQLiteConnection
(#"Data Source=C:\Users\YourUserName\AppData\Local\Google\Chrome\User Data\Default\History");
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
// cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;";
// Use the above query to get all the table names
cmd.CommandText = "Select * From urls";
SQLiteDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr[1].ToString());
}
In Windows form application with Datagridview tool - button click event
private void button1_Click(object sender, EventArgs e)
{
string google = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\Google\Chrome\User Data\Default\History";
string fileName = DateTime.Now.Ticks.ToString();
File.Copy(google, Application.StartupPath + "\\" + fileName);
using (SQLiteConnection con = new SQLiteConnection("DataSource = " + Application.StartupPath + "\\" + fileName + ";Versio=3;New=False;Compress=True;"))
{
con.Open();
//SQLiteDataAdapter da = new SQLiteDataAdapter("select url,title,visit_count,last_visit_time from urls order by last_visit_time desc", con);
SQLiteDataAdapter da = new SQLiteDataAdapter("select * from urls order by last_visit_time desc", con);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
con.Close();
}
try // File already open error is skipped
{
if (File.Exists(Application.StartupPath + "\\" + fileName))
File.Delete(Application.StartupPath + "\\" + fileName);
}
catch (Exception)
{
}
}
Reference source
Here i have copied the History file to Application startup path in order to avoid SQLite error "database is locked".
Used below code getting "Windows/x86_64" as a result
try
{
Class.forName ("org.sqlite.JDBC");
connection = DriverManager.getConnection ("jdbc:sqlite:/C:/Users/tarun.kakkar/AppData/Local/Google/Chrome/User Data/Default/History");
statement = connection.createStatement ();
resultSet = statement.executeQuery ("SELECT * FROM urls");
while (resultSet.next ())
{
System.out.println ("URL [" + resultSet.getString ("url") + "]" + ", visit count [" + resultSet.getString ("visit_count") + "]");
}
}
catch (Exception e)
{
e.printStackTrace ();
}
This piece of code might help you:
//Use sqlite for read chrome history
using System;
using System.IO;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
GetChromehistory();
Console.WriteLine();
}
public void GetChromehistory()
{
//Connection string
string path = #"\Google\Chrome\User Data\Default\History";
string chromehistorypath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + path;
if (File.Exists(chromehistorypath))
{
SQLiteConnection connection = new SQLiteConnection("Data Source=" + chromehistorypath + ";Version=3;New=False;Compress=True;");
connection.Open();
DataSet dataSet = new DataSet();
SQLiteDataAdapter adapter = new SQLiteDataAdapter("select * from urls order by last_visit_time desc", connection);
connection.Close();
adapter.Fill(dataSet);
var allHistoryItems = new List<ChromeHistoryItem>();
if (dataSet != null && dataSet.Tables.Count > 0 & dataSet.Tables[0] != null)
{
DataTable dt = dataSet.Tables[0];
foreach (DataRow historyRow in dt.Rows)
{
ChromeHistoryItem historyItem = new ChromeHistoryItem()
{
URL = Convert.ToString(historyRow["url"]),
Title = Convert.ToString(historyRow["title"])
};
// Chrome stores time elapsed since Jan 1, 1601 (UTC format) in microseconds
long utcMicroSeconds = Convert.ToInt64(historyRow["last_visit_time"]);
// Windows file time UTC is in nanoseconds, so multiplying by 10
DateTime gmtTime = DateTime.FromFileTimeUtc(10 * utcMicroSeconds);
// Converting to local time
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(gmtTime, TimeZoneInfo.Local);
historyItem.VisitedTime = localTime;
allHistoryItems.Add(historyItem);
}
}
}
}
}
public class ChromeHistoryItem
{
public string URL { get; set; }
public string Title { get; set; }
public DateTime VisitedTime { get; set; }
}

How can I paste selected data into another Excel sheet using OLEDB?

I have 2 Excel sheets. My requirement is, I have to copy all the data from one Excel sheet to another. Below is code snippet for the same, below code is copying and pasting all the data from one sheet to another in Excel, but its not pasting the data from A1 range.
I want the selected data to be pasted in another Excel sheet starting from 1st row. Also, I want to delete and insert fresh data every time the button is clicked, instead of appending into the same. Please help.
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.Common;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace TestExcelSheet
{
public partial class Form1 : Form
{
string path = #"C:\Users\Bhawesh\Documents\Visual Studio 2010\Projects\TestExcelSheet\DataValidationTest.xlsx";
string pathdestination = #"C:\Users\Bhawesh\Documents\Visual Studio 2010\Projects\TestExcelSheet\DataValidationTest - updated.xlsx";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//Source Path
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT [Job Code], [Job Name],Format([Start Date],'MM-DD-YYYY') as [Start Date], Format([End Date],'MM-DD-YYYY') as [End Date] FROM [Job$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
DataSet Job = new DataSet();
adapter.Fill(Job);
for (int iRowCount = 0; iRowCount <= Job.Tables[0].Rows.Count; iRowCount++)
{
string JobCode = "";
string JobName = "";
string StartDate = "";
string EndDate = "";
JobCode = Job.Tables[0].Rows[iRowCount]["Job Code"].ToString().Trim();
JobName = Job.Tables[0].Rows[iRowCount]["Job Name"].ToString().Trim();
StartDate = Job.Tables[0].Rows[iRowCount]["Start Date"].ToString().Trim();
EndDate = Job.Tables[0].Rows[iRowCount]["End Date"].ToString().Trim();
//Destination Path
string connectionStringdest = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathdestination + ";Extended Properties=Excel 12.0;";
DbProviderFactory factorydest = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapterdest = factorydest.CreateDataAdapter();
DbCommand insertCommand = factorydest.CreateCommand();
DbConnection connectiondest = factorydest.CreateConnection();
connectiondest.ConnectionString = connectionStringdest;
insertCommand.Connection = connectiondest;
adapterdest.InsertCommand = insertCommand;
if (connectiondest.State == ConnectionState.Closed)
{
connectiondest.Open();
}
if (Job.Tables.Count > 0 && Job.Tables[0].Rows.Count > 0)
{
insertCommand.CommandText = "Insert into [Job_updated$] values ('" + JobCode + "', '" + JobName + "', '" + StartDate + "', '" + EndDate + "') ";
//insertCommand.CommandText = "UPDATE [Job_updated$E1:E1] SET F1='MyNewCol';";
insertCommand.ExecuteNonQuery();
insertCommand.Dispose();
}
connectiondest.Close();
dataGridView1.DataSource = Job.Tables[0].DefaultView;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
but its not pasting the data from A1 range because first row is considered to be the headers for the table (sheet)
either create them manually or use getRange to do that.
// Create an array for the headers and add it to cells A1:C1.
object[] objHeaders = {"Order ID", "Amount", "Tax"};
m_objRange = m_objSheet.get_Range("A1", "C1");
m_objRange.Value = objHeaders;
in order to insert new data each time perform a delete command before inserting
oleDb does not sopport the delete command
Excel.Range ran = (Excel.Range)sheet.Rows[5, Type.Missing];
ran.Select();
ran.Delete(Excel.XlDirection.xlUp);
check this link for more functions on excel file Here

Categories