I'm trying to upload a PNG file to a mysql database blob type column.
I have searched everywhere and here is what I have so far, but I'm stuck...
I end up with System.byte[] in the database.
public static byte[] ArtworkRawData
StorageFile artworkfile = await openPicker.PickSingleFileAsync();
if (artworkfile != null)
{
artworkSet = true;
//var stream = await musicfile.OpenAsync(Windows.Storage.FileAccessMode.Read);
artworkFileBTN.Content = artworkfile.DisplayName;
var stream = await artworkfile.OpenAsync(FileAccessMode.Read);
var streamBytes = await artworkfile.OpenStreamForReadAsync();
var bytes = new byte[(int)streamBytes.Length];
ArtworkRawData = bytes;
var image = new BitmapImage();
await image.SetSourceAsync(stream);
artworkView.Source = image;
}
my query looks like this:
if (DBC.Insert("INSERT INTO music(artwork) values('" +UploadMusicDialog.ArtworkRawData + "')")){
//do some stuff
}
UPDATE
public bool Insert(string query)
{
//open connection
if (OpenConnection() == true)
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
CloseConnection();
}
}else
{
return false;
}
}
You should use this:
public bool Insert(string query, byte[] rawImage)
{
//open connection
if (OpenConnection() == true)
{
try
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlParameter parameter = new MySqlParameter("#rawImage", MySqlDbType.Blob);
parameter.Value = rawImage;
cmd.Parameters.Add(parameter);
cmd.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
CloseConnection();
}
}else
{
return false;
}
}
And call it like this:
if (DBC.Insert("INSERT INTO music(artwork) values(#rawImage)", UploadMusicDialog.ArtworkRawData))
{
//do some stuff
}
Anyway, it is not a good idea to have your query hardcoded like that. It is known for being highly unsecure.
Related
I try to pass the CodeNum object like parameter on query from this method:
protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
annotationView.CalloutOffset = new CGPoint(0, 0);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
((CustomMKAnnotationView)annotationView).Address = customPin.Address;
//Add First Line
((CustomMKAnnotationView)annotationView).AlertLevel = customPin.AlertLevel;
if (customPin.AlertLevel == 1)
{
annotationView.Image = UIImage.FromFile("green.png");
}
else if (customPin.AlertLevel == 2)
{
annotationView.Image = UIImage.FromFile("yellow.png");
}
else if (customPin.AlertLevel == 3)
{
annotationView.Image = UIImage.FromFile("orange.png");
}
else if (customPin.AlertLevel == 4)
{
annotationView.Image = UIImage.FromFile("red.png");
}
//Add Second Line
((CustomMKAnnotationView)annotationView).CodeNum = customPin.CodeNum;
}
annotationView.CanShowCallout = true;
configureDetailView(annotationView);
return annotationView;
}
When user clicks on some pin on the map to take a CodeNum and pass to query to get data from database. How to pass this parameter to OnDidSelectAnnotationView method ?
void OnDidSelectAnnotationView(object sender, MKAnnotationViewEventArgs e)
{
var customPin = GetCustomPin(annotation as MKPointAnnotation);
var result = DataBaseConnection(customPin.CodeNum);
MessagingCenter.Send<object, IEnumerable<AlertLevel>>(this, "PinSelected", result);
CustomMKAnnotationView customView = e.View as CustomMKAnnotationView;
customPinView = new UIView();
if (customView.Name.Equals("Xamarin"))
{
customPinView.Frame = new CGRect(0, 0, 200, 84);
customPinView.Center = new CGPoint(0, -(e.View.Frame.Height + 75));
e.View.AddSubview(customPinView);
}
}
In OnDidSelectAnnotationView method I get an error on this line of code:
var customPin = GetCustomPin(annotation as MKPointAnnotation);
Error CS0103: The name 'annotation' does not exist in the current context (CS0103)
My GetCustomPin method looks like this:
CustomPin GetCustomPin(MKPointAnnotation annotation)
{
var position = new Position(annotation.Coordinate.Latitude, annotation.Coordinate.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
This is my method who make connection to database and return list:
public IEnumerable<AlertLevel> DataBaseConnection(int mapCode)
{
string ConnectionString = "server=192.168.1.2;uid=UName;port=4443;pwd=Password;database=DBName;";
MySqlConnection Conn = new MySqlConnection(ConnectionString);
var listAlert = new List<AlertLevel>();
try
{
Conn.Open();
//replace(2) with mapCode
string query = "CALL Get_Alert_levels_Station(" + mapCode + ");";
MySqlCommand myCommand = new MySqlCommand(query, Conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
var currentData = new AlertLevel()
{
dateForecast = myReader.GetDateTime(0),
levelForecast = myReader.GetInt32(1)
};
listAlert.Add(currentData);
}
}
finally
{
myReader.Close();
Conn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Database Connection", "Not Connected ..." + Environment.NewLine + ex.ToString(), "OK");
}
return listAlert;
}
How to take CodeNum from clicked pin and pass to DataBaseConnection method like a variable mapCode?
example
Message can be sent by using MessagingCenter
You can use MessagingCenter through the link below
MessagingCenter
My web service was working fine. When a file is larger than 2MB, it throws System.AggregateException in System.Private.CoreLib.dll.
can you give me some suggestion?
Below is the exception:
Exception thrown: 'System.AggregateException' in System.Private.CoreLib.dll
An unhandled exception of type 'System.AggregateException' occurred in System.Private.CoreLib.dll
One or more errors occurred.
System.AggregateException
HResult=0x80131500
Message=One or more errors occurred. (The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.)
Source=System.Private.CoreLib
StackTrace:
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at sharepoint.Program.Main(String[] args) in C:\Users\Qihong.Kuang\source\repos\WebService\sharepoint\Program.cs:line 11
Inner Exception 1:
FaultException: The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.
static void Main(string[] args)
{
Console.WriteLine("Uploading...");
ServiceReference1.ServiceClient ws = new ServiceReference1.ServiceClient();
//something happened in this Async task;
ws.start_processAsync().Wait();
Console.WriteLine("Upload Finished!");
}
public class Service : IService
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public void start_process()
{
WebService ws = new WebService();
ws.GetCredentials();
}
}
public class WebService : System.Web.Services.WebService
{
OracleConnection con;
List<int> file_ids = new List<int>();
int file_id2;
string queryString;
OracleCommand cmd;
OracleDataReader dtr;
byte[] g_file = new byte[0];
string file_name;
ClientContext ctx;
public WebService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
public void StartProcess()
{
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromSeconds(30);
var timer = new System.Threading.Timer((e) =>
{
GetCredentials();
}, null, startTimeSpan, periodTimeSpan);
}
public void GetCredentials()
{
var siteUrl = "siteURL";
var user = "USER";
var password = "PASSWORD";
var pwd = new SecureString();
string docLib = "testtest";
foreach (var c in password) pwd.AppendChar(c);
var SPOCredentials = new SharePointOnlineCredentials(user, pwd);
var SPCredentials = new NetworkCredential(user, pwd);
string subfolderPath = GetSubFolder();
file_ids = GetFileID();
//string uploadLocation = GetFileName();
foreach (var file_id in file_ids)
{
file_id2 = file_id;
ExecuteType("file_name");
string uploadLocation = file_name;
using (ctx = new ClientContext(siteUrl))
{
try
{
ctx.Credentials = SPOCredentials;
ctx.ExecuteQuery();
}
catch (ClientRequestException)
{
ctx.Credentials = SPCredentials;
ctx.ExecuteQuery();
}
catch (NotSupportedException)
{
ctx.Credentials = SPCredentials;
ctx.ExecuteQuery();
Console.WriteLine("SharePoint On-Premise");
}
var library = ctx.Web.Lists.GetByTitle(docLib);
var fileBytes = new byte[] { };
//fileBytes = ReadData();
ExecuteType("blob");
FileStream fileStream;
fileBytes = g_file;
//fileStream = new FileStream(g_file, FileMode.Open);
var fileCreationInformation = new FileCreationInformation();
uploadLocation = string.Format("{0}/{1}", subfolderPath, uploadLocation);
uploadLocation = string.Format("{0}/{1}/{2}", siteUrl, docLib, uploadLocation);
fileCreationInformation.Content = fileBytes;
fileCreationInformation.Overwrite = true;
fileCreationInformation.Url = uploadLocation;
//Upload the file to root folder of the Document library
library.RootFolder.Files.Add(fileCreationInformation);
ctx.ExecuteQuery();
DeleteRecordAfterUploadToSharePoint();
}
}
}
public void ExecuteType(string executeType)
{
con = new OracleConnection(GetConnectionString());
queryString = GetQueryString();
try
{
con.Open();
OracleCommand cmd = new OracleCommand(queryString, con);
dtr = cmd.ExecuteReader();
while (dtr.Read())
{
if (executeType == "file_name")
{
file_name = Convert.ToString(dtr["file_name"]);
}
else if (executeType == "blob")
{
g_file = (byte[])dtr["actual_file"];
}
}
}
catch (Exception ex)
{
string showError = "Error: " + ex.Message;
}
finally
{
dtr.Close();
con.Close();
}
}
public void DeleteRecordAfterUploadToSharePoint()
{
con = new OracleConnection(GetConnectionString());
string queryString = GetDeleteQueryString();
try
{
con.Open();
cmd = new OracleCommand(queryString, con);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string showError = "Error: " + ex.Message;
}
finally
{
con.Close();
}
}
public List<int> GetFileID()
{
con = new OracleConnection(GetConnectionString());
string queryString = "select count(file_id), file_id from nfirs.sharepoint_file group by file_id";
OracleDataReader dtr = null;
try
{
con.Open();
OracleCommand cmd = new OracleCommand(queryString, con);
dtr = cmd.ExecuteReader();
while (dtr.Read())
{
file_ids.Add(Convert.ToInt32(dtr["file_id"]));
}
}
catch (Exception ex)
{
string showError = "Error: " + ex.Message;
}
finally
{
dtr.Close();
con.Close();
}
Console.WriteLine(file_ids);
return file_ids;
}
public int GetIndividualFileID()
{
return file_id2;
}
public string GetSubFolder()
{
DateTime dt = Convert.ToDateTime(DateTime.Now);
string year = dt.Year.ToString();
return year;
}
public string GetConnectionString()
{
return "Data Source=(DESCRIPTION =(connectionStringhere)";
}
public string GetQueryString()
{
return "select file_id, file_type, actual_file, file_name, file_mimetype, file_update_dttm, file_charset from nfirs.Sharepoint_File where file_id = " + GetIndividualFileID();
}
public string GetDeleteQueryString()
{
string deleteQuery = "delete from (" + GetQueryString() + ")";
return deleteQuery;
}
public string GetFileName()
{
con = new OracleConnection(GetConnectionString());
queryString = GetQueryString();
//OracleDataReader dtr = null;
//string file_name = "";
try
{
con.Open();
OracleCommand cmd = new OracleCommand(queryString, con);
dtr = cmd.ExecuteReader();
while (dtr.Read())
{
file_name = Convert.ToString(dtr["file_name"]);
}
}
catch (Exception ex)
{
string showError = "Error: " + ex.Message;
}
finally
{
dtr.Close();
con.Close();
}
return file_name;
}
public byte[] ReadData()
{
//OracleConnection con = new OracleConnection(GetConnectionString());
//List<int> file_ids = GetFileID();
//foreach(var file_id in file_ids)
//{
//}
string queryString = GetQueryString();
//OracleDataReader dtr = null;
//byte[] g_file = new byte[0];
try
{
con.Open();
cmd = new OracleCommand(queryString, con);
dtr = cmd.ExecuteReader();
while (dtr.Read())
{
g_file = (byte[])dtr["actual_file"];
}
}
catch (Exception ex)
{
string showError = "Error: " + ex.Message;
}
finally
{
dtr.Close();
con.Close();
}
return g_file;
}
}
Instead of using byte[], use memorystream
After couple days (like 3 days or so) my windows service just stops executing the system.timer events don't fire anymore but the service shows as running. Also my log files don't even get created so no errors are thrown and logged. I have try catches on the highest level as well as on the second highest level and also in the constructor, OnStart and OnStop. Please see my code below.
Any idea what could be causing this?
public partial class BetGamesFeedService : ServiceBase
{
private Timer _gamesTimer;
private Timer _nextDrawTimer;
private Timer _drawResultsTimer;
private Timer _plannedScheduleTimer;
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public BetGamesFeedService()
{
try
{
log4net.Config.XmlConfigurator.Configure();
//Games Timer
_gamesTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["GamesInterval"]));
_gamesTimer.Elapsed += GamesTimerOnElapsed;
_gamesTimer.Enabled = true;
//Next Draw Timer
_nextDrawTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["NextDrawInterval"]));
_nextDrawTimer.Elapsed += NextDrawTimerOnElapsed;
_nextDrawTimer.Enabled = true;
//Draw Results Timer
_drawResultsTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["DrawResultsInterval"]));
_drawResultsTimer.Elapsed += DrawResultsTimerOnElapsed;
_drawResultsTimer.Enabled = true;
//Planned Schedule Timer
_plannedScheduleTimer = new Timer(Convert.ToInt32(ConfigurationManager.AppSettings["PlannedScheduleInterval"]));
_plannedScheduleTimer.Elapsed += PlannedScheduleTimerOnElapsed;
_plannedScheduleTimer.Enabled = true;
InitializeComponent();
#if DEBUG
OnStart(null);
#endif
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
protected override void OnStart(string[] args)
{
try
{
_gamesTimer.Start();
_nextDrawTimer.Start();
_drawResultsTimer.Start();
_plannedScheduleTimer.Start();
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
protected override void OnStop()
{
try
{
_gamesTimer.Stop();
_nextDrawTimer.Stop();
_drawResultsTimer.Stop();
_plannedScheduleTimer.Stop();
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
private async void GamesTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var GamesOn = Convert.ToBoolean(ConfigurationManager.AppSettings["GamesIntervalOn"]);
if (!GamesOn) return;
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetGamesAndAddToDatabase();
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
private async void NextDrawTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetNextDrawAndAddToDatabase(Game.Lucky5);
await betGames.GetNextDrawAndAddToDatabase(Game.Lucky7);
await betGames.GetNextDrawAndAddToDatabase(Game.Lucky6);
await betGames.GetNextDrawAndAddToDatabase(Game.WheelOfFortune);
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
private async void DrawResultsTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky5);
await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky7);
await betGames.GetDrawResultsAndAddToDatabase(Game.Lucky6);
await betGames.GetDrawResultsAndAddToDatabase(Game.WheelOfFortune);
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
private async void PlannedScheduleTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
try
{
var betGames = new Bl.WindowsService.BetGames();
await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky5);
await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky7);
await betGames.GetScheduledDrawsAndAddToDatabase(Game.Lucky6);
await betGames.GetScheduledDrawsAndAddToDatabase(Game.WheelOfFortune);
}
catch(Exception ex)
{
log.Error(ex.ToString());
}
}
}
public class BetGames
{
private readonly int _partnerId =
Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PartnerId"]);
private readonly string _secretKey = System.Configuration.ConfigurationManager.AppSettings["SecretKey"];
private readonly int _shopId = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ShopId"]);
private readonly string[] _method =
{
"get_screen_urls", "get_games", "ticket_buy", "ticket_check",
"ticket_payout", "ticket_return"
};
private const string Language = "en";
private const string Currency = "eur";
private static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public async Task GetGamesAndAddToDatabase()
{
try
{
const int methodIndex = 1;
var request = new GetGamesRequest
{
partner_id = _partnerId,
method = _method[methodIndex],
language = Language,
timestamp = GetTimestamp(),
#params = new BaseParams
{
currency = Currency,
shop_id = _shopId
}
};
request.signature = GetSignature(methodIndex, request.timestamp, request.#params);
var api = new BetGamesAPI();
var response = await api.GetGames(request);
if (response == null)
{
log.Info("GetGamesAndAddToDatabase(): No Data Returned.");
return;
}
if (response.response_code != 200)
{
throw new Exception("response.response_code does not indicate success." + Environment.NewLine +
"Response Code: " + response.response_code + Environment.NewLine +
"Response Error: " + response.error_message);
}
var games =
new JavaScriptSerializer().Deserialize(response.response.ToString(), typeof(List<Bo.Models.Game>))
as List<Bo.Models.Game>;
//Add data to database
foreach (var game in games)
{
//#Id
var pId = new SqlParameter("#Id", SqlDbType.Int);
pId.Value = game.id;
//#Name
var pName = new SqlParameter("#Name", SqlDbType.VarChar);
pName.Value = game.name;
//#Type
var pType = new SqlParameter("#Type", SqlDbType.VarChar);
pType.Value = game.type;
//#Items
var dtItems = new DataTable();
dtItems.Columns.Add("Id", typeof(int));
dtItems.Columns.Add("Number", typeof(int));
dtItems.Columns.Add("Color", typeof(string));
foreach (var item in game.items)
{
dtItems.Rows.Add(item.id, item.number, item.color);
}
var pItems = new SqlParameter("#Items", SqlDbType.Structured);
pItems.Value = dtItems;
pItems.TypeName = "bg.ttItem";
//#Odds
var dtOdds = new DataTable();
dtOdds.Columns.Add("Code", typeof(int));
dtOdds.Columns.Add("ItemsCount", typeof(int));
dtOdds.Columns.Add("Name", typeof(string));
dtOdds.Columns.Add("Value", typeof(decimal));
foreach (var odd in game.odds)
{
dtOdds.Rows.Add(odd.code, odd.items_count, odd.name, odd.value);
}
var pOdds = new SqlParameter("#Odds", SqlDbType.Structured);
pOdds.Value = dtOdds;
pOdds.TypeName = "bg.ttOdd";
using (var db = new BetGamesEntities())
{
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "bg.InsertGameOddsAndItems";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(pId);
cmd.Parameters.Add(pName);
cmd.Parameters.Add(pType);
cmd.Parameters.Add(pItems);
cmd.Parameters.Add(pOdds);
db.Database.Connection.Open();
await cmd.ExecuteScalarAsync();
db.Database.Connection.Close();
}
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
private string GetSignature(int methodIndex, int timestamp, object _params)
{
var jsonEncodedObject = new JavaScriptSerializer().Serialize(_params);
var signatureBase = _partnerId + _method[methodIndex] + Language + timestamp + jsonEncodedObject;
//Perform hashing
using (var hmac = new HMACSHA256(Encoding.ASCII.GetBytes(_secretKey)))
{
var hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase));
return string.Concat(hash.Select(x => x.ToString("x2")));
}
}
private static int GetTimestamp()
{
return (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
public async Task GetNextDrawAndAddToDatabase(Game game)
{
try
{
var api = new BetGamesAPI();
var response = await api.GetNextDraw(game);
if (response == null)
{
log.Info("GetNextDrawAndAddToDatabase(" + game + "): No data returned. Draw Probably currently running.");
return;
}
var data =
new JavaScriptSerializer().Deserialize(response.draws.ToString(), typeof(List<Bo.Models.Draw>)) as List<Bo.Models.Draw>;
using (var db = new BetGamesEntities())
{
db.InsertOrUpdateDraw(data[0].code, data[0].time.AddHours(2), Convert.ToBoolean(data[0].is_returned),
data[0].video_url);
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
public async Task GetDrawResultsAndAddToDatabase(Game game)
{
try
{
var api = new BetGamesAPI();
using (var db = new BetGamesEntities())
{
var drawCode = db.GetDrawCode((int)game).FirstOrDefault();
if (drawCode == null) return;
var response = await api.GetDraws(game, drawCode.Value);
if (response == null)
{
log.Info("GetDrawResultsAndAddToDatabase(" + game + "): No Data Returned");
return;
}
//Insert Data
var data =
new JavaScriptSerializer().Deserialize(response.draws.ToString(), typeof(List<Bo.Models.Draw>)) as
List<Bo.Models.Draw>;
foreach (var draw in data)
{
//If this draw is Cancelled update the draw status to cancelled
if (draw.is_returned == 1)
{
db.InsertOrUpdateDraw(data[0].code, data[0].time.AddHours(2), Convert.ToBoolean(data[0].is_returned),
data[0].video_url);
}
//if we have results for this draw
if (draw.results_entered == 1)
{
//#DrawCode
var pDrawCode = new SqlParameter("#DrawCode", SqlDbType.BigInt) { Value = draw.code };
//#Results
var dtResults = new DataTable();
dtResults.Columns.Add("BallNumber");
dtResults.Columns.Add("BallColor");
foreach (var result in draw.results)
{
dtResults.Rows.Add(result.Number, result.Color);
}
var pResults = new SqlParameter("#Results", SqlDbType.Structured)
{
Value = dtResults,
TypeName = "bg.ttDrawResult"
};
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "bg.InsertDrawResults";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(pDrawCode);
cmd.Parameters.Add(pResults);
db.Database.Connection.Open();
cmd.ExecuteScalar();
db.Database.Connection.Close();
}
}
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
public async Task GetScheduledDrawsAndAddToDatabase(Game game)
{
try
{
var api = new BetGamesAPI();
var response = await api.GetScheduledDraws(game);
if (response == null)
{
log.Info("GetScheduledDrawsAndAddToDatabase(" + game + "): No data returned. Draw Probably currently running.");
return;
}
var data =
new JavaScriptSerializer().Deserialize(response, typeof(List<Bo.Models.ScheduledDraw>)) as List<Bo.Models.ScheduledDraw>;
using (var db = new BetGamesEntities())
{
var scheduledDrawTable = new DataTable();
scheduledDrawTable.Columns.Add("Code", typeof(long));
scheduledDrawTable.Columns.Add("Time", typeof(DateTime));
foreach (var draw in data)
{
scheduledDrawTable.Rows.Add(draw.number, draw.time.AddHours(2));
}
var Draws = new SqlParameter("#Draws", SqlDbType.Structured);
Draws.Value = scheduledDrawTable;
Draws.TypeName = "bg.ttDraw";
var cmd = db.Database.Connection.CreateCommand();
cmd.CommandText = "bg.InsertOrUpdateScheduledDraws";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(Draws);
db.Database.Connection.Open();
cmd.ExecuteScalar();
db.Database.Connection.Close();
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
}
}
I have a series of asynchronous functions that are cascaded, but when it finishes executing the last, it does not return the values to the previous ones.
This is where my first call is run. This is a WebAPI function and always comes to an end.
[HttpGet]
[Route("integracao/iniciar")]
public IHttpActionResult FazerIntegrar()
{
try
{
Integrar objIntegrar = new Integrar();
return Ok(objIntegrar.Integra());
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
so my function is in my library is called. Within my function I have a for executing only once. The flow is never resumed by it to continue the loop
public async Task<bool> Integra()
{
var files = Directory.GetFiles(#"C:\inetpub\wwwroot\Atendup\Arquivos\Backup\");
bool retorno = false;
if (files != null)
{
foreach (var item in files)
{
retorno = false;
using (StreamReader sr = new StreamReader(item))
{
if (sr != null)
{
while (sr.EndOfStream == false)
{
string line = await sr.ReadLineAsync();
string[] grupo = line.Split(new[] { "#*#" }, StringSplitOptions.None);
procData objProc = new procData();
objProc.proc = grupo[0];
objProc.name = JsonConvert.DeserializeObject<List<string>>(grupo[1]);
objProc.valor = JsonConvert.DeserializeObject<List<object>>(grupo[2]);
objProc.tipo = JsonConvert.DeserializeObject<List<Type>>(grupo[3]);
_context = new IntegrarRepository("online_pedidopizza");
retorno = await _context.IntegrarAsync(objProc);
//retorno = await _context.IntegrarAsync(objProc);
}
}
}
if (retorno == true)
{
await DeleteAsync(item);
}
}
}
return retorno;
}
I have a third function just to mediate with the repository
public async Task<bool> IntegrarAsync(procData objProc)
{
return await this.SendIntegrarAsync(objProc);
}
And finally, communication with the database, all code is executed correctly. Debugging you can get to the end of this fourth function but then the debug stop and does not go back to the beginning
protected async Task<bool> SendIntegrarAsync(procData parametro)
{
bool retorno = false;
using (SqlConnection conn = new SqlConnection(""))
{
using (SqlCommand cmd = new SqlCommand(parametro.proc, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
if (parametro != null)
{
for (int i = 0; i < parametro.name.Count; i++)
{
AdicionaParametro(cmd, parametro.name[i], parametro.valor[i], parametro.tipo[i]);
}
}
try
{
cmd.CommandTimeout = 300;
await conn.OpenAsync().ConfigureAwait(false);
var resultado = await cmd.ExecuteScalarAsync().ConfigureAwait(false);
if (resultado != null)
{
retorno = Convert.ToBoolean(resultado);
}
}
catch (Exception ex)
{
Logs objLog = new Logs()
{
metodo = MethodBase.GetCurrentMethod().Name,
classe = this.GetType().Name,
dados = parametro,
data = DateTime.Now,
mensagem = ex.Message,
exception = ex.InnerException == null ? "" : ex.InnerException.ToString()
};
objLog.Adiciona();
string name = DateTime.Now.ToBinary().ToString();
using (StreamWriter sw = new StreamWriter(#"C:\inetpub\wwwroot\Atendup\Arquivos\Backup\" + name + ".txt"))
{
string line = "";
line += parametro.proc + "#*#";
line += JsonConvert.SerializeObject(parametro.name) + "#*#";
line += JsonConvert.SerializeObject(parametro.valor) + "#*#";
line += JsonConvert.SerializeObject(parametro.tipo) + "#*#";
sw.WriteLine(line);
}
}
}
}
return retorno;
}
What should I have to do? Thanks
Your Web Api call is not async try changing it to:
[HttpGet]
[Route("integracao/iniciar")]
public async Task<IHttpActionResult> FazerIntegrar()
{
try
{
Integrar objIntegrar = new Integrar();
return Ok(await objIntegrar.Integra());
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
For many hours now I have lost it over this same error no matter what I change.
I'm trying to make a command line application that will retrieve info from a database based off of two argument inputs, the modname and the optional author. The queries are all handled in the jobs.cs file. The entry-point file calls the method beginJob() which gets the target modname and author (if specified) to query. What's different from the hundred or so other posts I've read here is that the first query issued works completely fine, and I'm sure to close the reader and connection. (Won't close connection every time in production, but I did here for debugging purposes). The next time I call the connection it results in this error.
System.InvalidOperationException: Connection must be valid and open.
at MySql.Data.MySqlClient.ExceptionInterceptor.Throw(Exception exception)
at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex)
at MySql.Data.MySqlClient.MySqlCommand.CheckState()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()
at vmcmod.Job.queryAuthor(String authorUID) in F:\Projects\VisualStudio\VMC-MOD\vmcmod\job.cs:line 235
at vmcmod.Job.StartJob() in F:\Projects\VisualStudio\VMC-MOD\vmcmod\job.cs:line 47
at vmcmod.Job.queryModAndAuthor(String modname, String author) in F:\Projects\VisualStudio\VMC-MOD\vmcmod\job.cs:line 205
at vmcmod.Job.beginJob() in F:\Projects\VisualStudio\VMC-MOD\vmcmod\job.cs:line 27
at vmcmod.VMCMOD.parseArgs() in F:\Projects\VisualStudio\VMC-MOD\vmcmod\vmcmod.cs:line 58
Some posts I've looked at but don't seem to help:
C# Mysql Connection must be valid and open
Connection must be valid and open error
C# Query: 'System.InvalidOperationException' | Additional information: Connection must be valid and open
C# Source Files (Please try and not cringe too hard, this is my first C# application):
jobs.cs [updated]
using MySql.Data.MySqlClient;
using System;
namespace vmcmod
{
class Job
{
public bool checkInput()
{
if (Global.currentJobTargetModname == "undefined")
{
Utils.consoleLog("The mod name is required.", 3);
return false;
}
else
{
return true;
}
}
public void beginJob()
{
string targetModname = Global.currentJobTargetModname.ToLower();
string targetModAuthor = Global.currentJobTargetAuthor.ToLower();
if (targetModAuthor != "undefined")
{
queryModAndAuthor(targetModname, targetModAuthor);
Utils.consoleLog("Job Call. (Author defined)", 4);
}
else
{
queryMod(targetModname);
Utils.consoleLog("Job Call. (Author undefined)", 4);
}
}
private void StartJob()
{
string author = null;
string targetModAuthor = Global.currentJobTargetAuthor.ToLower();
Utils.consoleLog("Mod exists.", 5);
if (targetModAuthor == "undefined")
{
author = "(None; First in row)";
}
else
{
queryAuthor(Global.queryResModAuthorID);
author = "'" + Global.queryResModAuthor + "' (UUID:" + Global.queryResModAuthorID + ") ";
}
var collaborators_obj = Newtonsoft.Json.Linq.JObject.Parse(Global.queryResModCollab);
var tags_obj = Newtonsoft.Json.Linq.JObject.Parse(Global.queryResModTags);
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("MOD INSTALL SPECIFICATIONS:");
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine(" Mod Name: '" + Global.queryResModName + "'");
Console.Write(" Mod Author: " + author);
if (Global.queryResModAuthorVerified == true && targetModAuthor != "undefined")
{
Utils.consoleTag("*VERIFIED*", ConsoleColor.Green);
}
if (Global.queryResModAuthorVerified == false && targetModAuthor != "undefined")
{
Utils.consoleTag("*UNVERIFIED*", ConsoleColor.Red);
}
Console.Write("\n");
Console.WriteLine(" Mod Version: " + Global.queryResModVersion);
Console.WriteLine(" Installations: " + Global.queryResModInstalls);
Console.WriteLine(" Description:\n " + Global.queryResDescription);
Console.WriteLine(" Mod UUID: " + Global.queryResModUid);
if (Global.advInfo == true)
{
Console.WriteLine(" Rep. Entry #" + Global.queryResModID);
Console.WriteLine(" Mod Created On: " + Utils.UnixTimeStampToDateTime(Convert.ToDouble(Global.queryResDateCreated)));
Console.WriteLine(" Mod Last Modified On: " + Utils.UnixTimeStampToDateTime(Convert.ToDouble(Global.queryResDateLastModf)));
Console.WriteLine(" Tags: \n " + Convert.ToString(tags_obj["tags"]));
Console.WriteLine(" Collaborators: \n " + Convert.ToString(collaborators_obj["collaborators"]));
}
Utils.consoleSeparator();
bool user_response = Utils.consoleAskYN("Are you sure you want to install this mod?");
if (user_response == true)
{
queryGetModJSON(Global.queryResModUid);
Utils.consoleLog("JSON Data: "+Global.queryResModJSON,5);
//FileIO fio = new FileIO();
//fio.jsonToFiles(fio.jsonToArray(Global.queryResModJSON));
}
else
{
Utils.consoleSetKeyExit();
}
}
private void queryGetModJSON(string uuid)
{
var dbCon = new DBConnection();
if (dbCon.IsConnect() == false)
{
Utils.consoleLog("Unable to query repository or no results.", 3);
Utils.consoleSetKeyExit();
}
else
{
string q = "SELECT data_json FROM vmcmod_repository_data WHERE uid='" + uuid + "' LIMIT 1;";
MySqlCommand cmd = new MySqlCommand(q, dbCon.Connection);
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
Utils.consoleLog("Mod data not found.", 3);
reader.Close();
dbCon.Close();
}
else
{
while (reader.Read())
{
Global.queryResModJSON = reader.GetString(0);
}
reader.Close();
dbCon.Close();
}
}
}
private void queryMod(string modname)
{
var dbCon = new DBConnection();
if (dbCon.IsConnect() == false)
{
Utils.consoleLog("Unable to query repository or no results.", 3);
Utils.consoleSetKeyExit();
}
else
{
string q = "SELECT id,uid,author_id,mod_name,status,dependencies_json,description,mod_version,date_created,date_last_modified,collaborators,tags_json,installs FROM vmcmod_repository_info WHERE mod_name LIKE'" + modname + "' LIMIT 1;";
MySqlCommand cmd = new MySqlCommand(q, dbCon.Connection);
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
Utils.consoleLog("Mod not found.", 3);
reader.Close();
dbCon.Close();
}
else
{
while (reader.Read())
{
Global.queryResModInstalls = reader.GetInt32(12);
Global.queryResModTags = reader.GetString(11);
Global.queryResModCollab = reader.GetString(10);
Global.queryResDateLastModf = reader.GetInt32(9);
Global.queryResDateCreated = reader.GetInt32(8);
Global.queryResModVersion = reader.GetFloat(7);
Global.queryResDescription = reader.GetString(6);
Global.queryResModDependencies = reader.GetString(5);
Global.queryResModStatus = reader.GetInt16(4);
Global.queryResModName = reader.GetString(3);
Global.queryResModAuthorID = reader.GetString(2);
Global.queryResModUid = reader.GetString(1);
Global.queryResModID = Convert.ToInt32(reader.GetInt32(0));
}
reader.Close();
dbCon.Close();
StartJob();
}
}
}
private void queryModAndAuthor(string modname, string author)
{
var dbCon = new DBConnection();
if (dbCon.IsConnect() == false)
{
Utils.consoleLog("Unable to query repository or no results.", 3);
Utils.consoleSetKeyExit();
}
else
{
string q = "SELECT id,uid,author_id,mod_name,status,dependencies_json,description,mod_version,date_created,date_last_modified,collaborators,tags_json,installs FROM vmcmod_repository_info WHERE mod_name LIKE'" + modname + "' LIMIT 1;";
MySqlCommand cmd = new MySqlCommand(q, dbCon.Connection);
var reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
Utils.consoleLog("Mod not found.", 3);
reader.Close();
dbCon.Close();
}
else
{
while (reader.Read())
{
Global.queryResModInstalls = reader.GetInt32(12);
Global.queryResModTags = reader.GetString(11);
Global.queryResModCollab = reader.GetString(10);
Global.queryResDateLastModf = reader.GetInt32(9);
Global.queryResDateCreated = reader.GetInt32(8);
Global.queryResModVersion = reader.GetFloat(7);
Global.queryResDescription = reader.GetString(6);
Global.queryResModDependencies = reader.GetString(5);
Global.queryResModStatus = reader.GetInt16(4);
Global.queryResModName = reader.GetString(3);
Global.queryResModAuthorID = reader.GetString(2);
Global.queryResModUid = reader.GetString(1);
Global.queryResModID = Convert.ToInt32(reader.GetInt32(0));
}
reader.Close();
dbCon.Close();
StartJob();
}
}
}
private bool queryCheckAuthorExists(string author)
{
var dbCon = new DBConnection();
string q = "SELECT * FROM vmcmod_users WHERE username='"+author+ "' AND is_author=true LIMIT 1;";
MySqlCommand cmd = new MySqlCommand(q, dbCon.Connection);
var reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Utils.consoleLog("Author not found.", 3);
reader.Close();
dbCon.Close();
return false;
}
else
{
Utils.consoleLog("Author found.", 4);
reader.Close();
dbCon.Close();
return true;
}
}
private void queryAuthor(string authorUID)
{
var dbCon = new DBConnection();
string q = "SELECT username,is_verified_user FROM vmcmod_users WHERE uid='" + authorUID + "' AND is_author=true LIMIT 1;";
MySqlCommand cmd = new MySqlCommand(q, dbCon.Connection);
var reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Utils.consoleLog("Author not found.", 3);
reader.Close();
dbCon.Close();
}
else
{
while (reader.Read())
{
Global.queryResModAuthor = reader.GetString(0);
Global.queryResModAuthorVerified = reader.GetBoolean(1);
}
Utils.consoleLog("Author found.", 4);
reader.Close();
dbCon.Close();
}
}
}
}
dbinterface.cs (this wasn't written by me, rather taken and edited from a post on stackoverflow, here) [updated]
using MySql.Data.MySqlClient;
using System;
namespace vmcmod
{
public class DBConnection
{
public DBConnection()
{
}
public string Password { get; set; }
private MySqlConnection connection = null;
public MySqlConnection Connection
{
get { return connection; }
}
public bool IsConnect()
{
bool result = true;
if (Connection == null)
{
string connString = "Server=...; Port=...; Database=...; Uid=...; Pwd=...;";
connection = new MySqlConnection(connString);
try
{
connection.Open();
Utils.consoleLog("Connected to repository.", 4);
result = true;
}
catch (Exception e)
{
Utils.consoleLog("Error occured while connecting to repository.", 3);
Utils.consoleLog("MySQL Exception: "+e,5);
result = false;
}
}
return result;
}
public void Close()
{
connection.Close();
connection = null;
}
}
}
global.cs (global variable storage)
using System;
namespace vmcmod
{
class Global
{
internal const float version = 0.1F;
internal static string currentJobWorld = "New World";
internal static string currentJobTargetModname = "undefined";
internal static string currentJobTargetAuthor = "undefined";
internal static string currentJobProfile = "default";
internal static int currentJobAccountPIN;
internal static bool verbose = false;
internal static bool debug = false;
internal static bool advInfo = false;
internal static bool queryResModAuthorVerified = false;
internal static string queryResModUid;
internal static string queryResModAuthorID;
internal static string queryResModAuthor;
internal static string queryResModName;
internal static string queryResModDependencies = "{\"dependencies\":[]}";
internal static int queryResModStatus;
internal static float queryResModVersion;
internal static string queryResDescription = "None provided.";
internal static int queryResDateCreated;
internal static int queryResDateLastModf;
internal static int queryResModID;
internal static string queryResModCollab = "{\"collaborators\":[]}";
internal static string queryResModTags = "{\"tags\":[]}";
internal static int queryResModInstalls;
internal static string queryResModJSON = "{}";
}
}
The quick and dirty solution would be to change:
public void Close()
{
connection.Close();
}
to:
public void Close()
{
connection.Close();
connection = null;
}
Also, remove this code:
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if (_instance == null)
_instance = new DBConnection();
return _instance;
}
and rather than use DBConnection.Instance, just use new DBConnection();
And change:
public MySqlConnection Connection
{
get { return connection; }
}
to:
public MySqlConnection Connection
{
get {
IsConnect();
return connection; }
}
and change:
public bool IsConnect()
{
bool result = true;
if (Connection == null)
to:
public bool IsConnect()
{
bool result = true;
if (connection == null)
I see you are using singletne pattern for DBConnection this is not a good idea.
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if (_instance == null)
_instance = new DBConnection();
return _instance;
}
You might want to check this answer out for more information: https://stackoverflow.com/a/814606/8143718
As per #mjwills' response, the DB interface script I'd swiped was quite funky and only allowed one instance at a time.
Working DB Interface
using MySql.Data.MySqlClient;
using System;
namespace vmcmod
{
public class DBConnection
{
public DBConnection()
{
}
public string Password { get; set; }
private MySqlConnection connection = null;
public MySqlConnection Connection
{
get
{
IsConnect();
return connection;
}
}
public bool IsConnect()
{
bool result = true;
if (connection == null)
{
string connString = "Server=...; Port=...; Database=...; Uid=...; Pwd=...;";
connection = new MySqlConnection(connString);
try
{
connection.Open();
Utils.consoleLog("Connected to repository.", 4);
result = true;
}
catch (Exception e)
{
Utils.consoleLog("Error occured while connecting to repository.", 3);
Utils.consoleLog("MySQL Exception: "+e,5);
result = false;
}
}
return result;
}
public void Close()
{
connection.Close();
connection = null;
}
}
}