xamarin mysql command show Index was outside the bounds of the array - mysql

I'm trying to insert data into mysql database.
I'm using mysqlConnector.
But after I confirm insertion with my code.
Debugger returns Index was outside the bounds of the array
Here is my code of insertion:
if (co.OpenConnection() == true)
{
string query = "INSERT INTO inventory (flItem) VALUES('" + ItemName.Text + "');";
MySqlCommand cmd = new MySqlCommand(query, co.connection);
//MySqlDataReader reader = cmd.ExecuteReader();
cmd.ExecuteReader();
await DisplayAlert("TEST", cmd.CommandText, "OK");
await Navigation.PushAsync(new AppShell());
}
Thanks for any help in advance.

Related

parsing issue with JSON data from SQL 2017 to MongoDB

I am working on c# utility to migrate data from SQL server 2017 to MongoDB. Below are steps I am following
1) Getting data from SQL server in JSON format (FOR JSON AUTO)
2) Parsing into BSON document
3) Then trying to insert into MongoDB
But I am getting error while reading JSON data from SQL.
My Json data is combination of root attributes as well as nested objects.
So Its dynamic data, that I want to PUSH as it is to MongoDB.
string jsonData = string.Empty;
foreach (var userId in userIdList)
{
using (SqlConnection con = new SqlConnection("Data Source=;Initial Catalog=;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("Usp_GetUserdata", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userId", SqlDbType.Int).Value = userId;
con.Open();
var reader = cmd.ExecuteReader();
jsonResult = new StringBuilder();
//cmd.ExecuteNonQuery();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0));
jsonData = reader.GetValue(0).ToString();
File.WriteAllText(#"c:\a.txt", jsonResult.ToString());
File.WriteAllText(#"c:\a.txt",jsonData);
jsonData.TrimEnd(']');
jsonData.TrimStart('[');
//Create client connection to our MongoDB database
var client = new MongoClient(MongoDBConnectionString);
//Create a session object that is used when leveraging transactions
var session = client.StartSession();
//Create the collection object that represents the "products" collection
var employeeCollection = session.Client.GetDatabase("mongodev").GetCollection<BsonDocument>("EmpData");
//Begin transaction
session.StartTransaction();
try
{
dynamic resultJson = JsonConvert.DeserializeObject(result);
var document = BsonSerializer.Deserialize<BsonDocument>(resultJson);
//MongoDB.Bson.BsonDocument document
// = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonResult);
employeeCollection.InsertOneAsync(document);
//BsonArray pipeline =
// MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonArray>(jsonData);
//var documents = pipeline.Select(val => val.AsBsonDocument);
//employeeCollection.InsertManyAsync(documents);
session.CommitTransaction();
}
catch (Exception e)
{
Console.WriteLine(e);
session.AbortTransaction();
throw;
}
}
}
}
}
}

How to get salt from MySql database using Asp.net?

How can I retrieve salt from MySql database using Asp.Net ?
I want to use that retrieved salt to add to the user entered password to generate an SHA256 hash and then authenticate the user.
Here is what I am trying to do to fetch the salt:
String userNameEntered = UserN_TextBox.Text;
String passwordEntered = Password_TextBox.Text;
String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
connection = new MySqlConnection(connectionString);
connection.Open();
MessageBox.Show("Successfully connected to database");
String queryString = "select salt from xyz.abc_table where salt = #Salt";
command = new MySqlCommand(queryString, connection);
command.Parameters.AddWithValue("#Salt", queryString);
reader = command.ExecuteReader();
Response.Write("Salt retrived is" + reader);
reader.Close();
connection.Close();
When I execute this code, it returns the MySql Data Reader library rather than the salt in the database....
Thanks in advance... :)
Here I have solved my problem. Here is the solution to the problem. It might help someone:
try
{
String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
connection = new MySqlConnection(connectionString);
connection.Open();
MessageBox.Show("Successfully connected to database");
String queryString = "select salt from xyz.abc_table where email_address = #E_Address";
command = new MySqlCommand(queryString, connection);
command.Parameters.AddWithValue("#E_Address", UserN_TextBox.Text);
reader = command.ExecuteReader();
if (reader.Read())
{
Response.Write("Retrived Salt is " + reader["salt"]);
reader.Close();
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" +ex);
}

Checking Null Cells within MySql Table

i just wander if there is away to check MySql asp Table if its Cells has Values or Not .
i'v used this to return if Database has Row/Record there
string ConnectionString = #"Server=MYSQL5011.Smarterasp.net;Database=db_9d6c52_ahmed;Uid=9d6c52_ahmed;Pwd=******;";
MySqlConnection GetConnection = new MySqlConnection(ConnectionString);
GetConnection.Open();
string VoiceorScreenSearch = "Select User_Voice ,User_Screen From User where User_Stat=#UserStat";
MySqlCommand Comand = new MySqlCommand(VoiceorScreenSearch, GetConnection);
Comand.Parameters.AddWithValue(#"UserStat", key);
MySqlDataReader ReadData = Comand.ExecuteReader();
if (ReadData.HasRows)
{
hasrowsornot = true;
}
but i need it to return if Cell[1] is null or Has data !, My Cells Datatype is BLOB
and tips of doing this ? , will be helpful
Thanks
You can try like this:
if (!ReadData.IsDbNull(yourfield)) {
var value = ReadData.GetString(yourfield);
// some code
}

Unable to load huge files using Load Data infile local into mysql

I tried to load huge data file eg 10 mb files into the db using Load Data Local Infile into mysql using a windows service. But it failed and the windows service stopped without any exception. I tried with files of small size such as 2 mb and it succeded.
Is there any way I can load huge files into the mysql db? And what may be the reason for the windows service to stop?
here is my code..
public int UpdateDataBase(string query, string filename, Logger swLog)
{
int status = 0;
using (MySqlConnection myconnection = new MySqlConnection(connectionCdrBank))
{
try
{
myconnection.ConnectionTimeout = 1000;
myconnection.Open();
myconnection.BeginTransaction();
MySqlCommand mycommand = new MySqlCommand("ClearTempTable", myconnection);
mycommand.CommandType = CommandType.StoredProcedure;
status = mycommand.ExecuteNonQuery();
MySqlCommand mycommand1 = new MySqlCommand(query, myconnection);
mycommand1.CommandTimeout = 1000;
status = mycommand1.ExecuteNonQuery();
MySqlCommand mycommand2 = new MySqlCommand("InsertToCdrDetailsTempTable", myconnection);
mycommand2.CommandType = CommandType.StoredProcedure;
mycommand2.CommandTimeout = 1000;
status = Convert.ToInt32(mycommand2.ExecuteScalar());
myconnection.Commit();
myconnection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
if (myconnection.State == ConnectionState.Open)
myconnection.Rollback();
status = (ex.Message.IndexOf("Duplicate entry") != -1) ? -1000 : 0;
swLog.WriteErrorToLog("");
swLog.WriteErrorToLog("Error while saving: " + ex.Message);
mail.SentMail("Error while saving:", ex.Message);
swLog.CloseLogger();
}
}
return status;
}
where query is
LOAD DATA LOCAL INFILE 'a.txt' INTO TABLE tbl_cdrload" FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';
I'm loading up to 100 MB files into MySQL Blob fields. And this is just my artificial limit.
So, 10MB files should not be a problem.
Did you set max_allowed_packet correctly?
What do you use to load the files? Your own code or some tool? What MySQL Connector?

Convert SqlCommand Output to List<MyType>?

I am using an ADO.NET SqlCommand with a single SqlDbType.Structured parameter to send a table-valued parameter to a sproc. The sproc returns many rows, which I need to get into a strongly-Typed List of . What is the best way to convert the result set (whether DataTable from a DataAdapter or DataReader bits) into List?
Thanks.
You can use LINQ with a DataReader:
var list = reader.Cast<IDataRecord>()
.Select(dr => new YourType { Name = dr.GetString(0), ... })
.ToList();
The most efficient way is using datareader:
var items = new LinkedList<MyClass>();
using(var connection = GetConnection()) {
using(var cmd = connection.CreateCommand()){
cmd.CommandText = "... your SQL statement ...";
// ... add parameters
cnn.Open();
using(var reader = cmd.ExecuteReader()) {
// accessing values via number index is most efficient
//gets index of column with name "PrimaryKey"
var ndxPrimaryKey = reader.GetOrdinal("PrimaryKey");
var ndxColumn1 = reader.GetOrdinal("Column1");
var ndxColumn2 = reader.GetOrdinal("Column2");
while(reader.Read()) {
var item = new MyClass();
// returns value of column "PrimaryKey" typed to nullable Guid
item.PrimaryKey = reader.GetValue(ndxPrimaryKey) as Guid?;
item.Column1 = reader.GetValue(ndxColumn1) as string;
item.Column2 = reader.GetValue(ndxColumn2) as int?;
items.AddLast(item);
}
}
cnn.Close();
}
}
return items;
i think you can use Dapper to convert a query to a class.
for more information see my answer in this link