I try to change my database connection method with data from API and want to remove connection to database.
This is my database connection and I want to replace data from database with data from API.
public IEnumerable<AlertLevel> DataBaseConnection(int mapCode)
{
string ConnectionString = "server=192.168.1.1;uid=user;port=3333;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;
}
This is my methods with API data:
string GenerateRequestUri(string endpoint)
{
string requestUri = endpoint;
requestUri += $"?id=16";
return requestUri;
}
string GenerateRequestUriStations(string endpoint)
{
string requestUri = endpoint;
requestUri += $"stations";
return requestUri;
}
public WaterBindingData GetData()
{
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var item in reusult.WaterData.Ardaforecast[0].Items)
{
item.DateTimeForecast.ToString();
item.AlertLevelForecast.ToString();
}
return reusult;
}
I want to put inside in DataBaseConnection method my API logic and want to put item.DateTimeForecast.ToString(); and item.AlertLevelForecast.ToString(); in AlertLevel and also I don't know how to put dynamic variable in GenerateRequestUri(string endpoint): requestUri += $"?id=16"; 16 Have to be mapCode
I assume you want to do something like this
string GenerateRequestUri(string endpoint, mapCode)
{
string requestUri = endpoint;
requestUri += $"?id={mapCode}";
return requestUri;
}
public IEnumerable<AlertLevel> GetDataFromAPI(int mapCode)
{
var listAlert = new List<AlertLevel>();
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint), mapCode);
foreach (var item in reusult.WaterData.Ardaforecast[0].Items)
{
var currentData = new AlertLevel()
{
dateForecast = item.DateTimeForecast.ToString(),
levelForecast = item.AlertLevelForecast.ToString()
};
listAlert.Add(currentData);
}
return listAlert;
}
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'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.
I have this app. Is connected with one database and sending notification to android devices. I want to keep this app always open and check the database for new record. The only idea i had is to put in one infinity loop like while(true) but i have warning in the line with connection.Open(); about memory and the program is stopping.
namespace AndroidParse
{
class Program
{
static void Main(string[] args)
{
//SqlDataReader reader;
SqlConnection conn = new SqlConnection();
string queryString = "SELECT TOP 1 device_id FROM Temp ORDER BY ID_Requests DESC";
string connectionString = "XXXX";
while (true)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(reader[0]);
bool isPushMessageSend = false;
string postString = "";
string urlpath = "https://api.parse.com/1/push";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlpath);
postString = "{\"data\": { \"alert\": \"Finally is working\" },\"where\": { \"device_id\": \"" + reader[0] + "\" }}";
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = postString.Length;
httpWebRequest.Headers.Add("X-Parse-Application-Id", "XXXX");
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", "XXXX");
httpWebRequest.Method = "POST";
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
JObject jObjRes = JObject.Parse(responseText);
if (Convert.ToString(jObjRes).IndexOf("true") != -1)
{
isPushMessageSend = true;
}
}
//--------------------------------------------------
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader1;
cmd.CommandText = "delete from Temp where ID_Requests in (select top 1 ID_Requests from Temp order by ID_Requests desc)";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader1 = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
//--------------------------------------------------
Console.ReadLine();
}
}
finally
{
reader.Close();
}
connection.Close();
}
}
}
private static void println()
{
throw new NotImplementedException();
}
}
}
Using a SqlDependency object like Denis Reznik suggested is a great solution.
A few things to keep in mind:
SqlDependency requires the SQL Server Service Broker service to be running on SQL Server (more details here: https://msdn.microsoft.com/en-us/library/ms172133(v=vs.110).aspx)
The queries that can be used in the SqlCommand are essentially continuously executed on the server... Because of this there is a handful of limitations on what the query can do (e.g. no aggregates). More details in the SO answer from Smudge202 here: What are the limitations of SqlDependency
I have found that using SqlDependency to simply notify of a change, and then acting on that by calling data access methods, etc... is easier than attempting to actually use the query to retrieve data. So, in your example, you may want to let the SqlDependency notify there is a change, then create a separate data access method / sp / etc... to retrieve details like the device_id.
Here is a sample that is sort of based on your code above... It will probably require a few tweaks. Good Luck!
namespace AndroidParse
{
public class DbMonitor
{
private readonly string _connectionString = ConfigurationManager.ConnectionStrings["XXXXX"].ConnectionString;
private SqlDependency _dependency;
private SqlConnection _conn;
private SqlCommand _command;
public void MonitorDatabase()
{
SqlDependency.Start(_connectionString);
// Open DB Connection
using (_conn = new SqlConnection(_connectionString))
{
// Setup SQL Command
using (_command = new SqlCommand("SELECT TOP 1 device_id FROM Temp ORDER BY ID_Requests DESC", _conn))
{
// Create a dependency and associate it with the SqlCommand. *** MAGIC ****
_dependency = new SqlDependency(_command);
// Subscribe to the SqlDependency event.
_dependency.OnChange += HandleDatabaseChange;
// Execute
_command.Connection.Open();
_command.ExecuteReader();
}
}
}
public void Stop()
{
SqlDependency.Stop(_connectionString);
}
private void HandleDatabaseChange(object sender, SqlNotificationEventArgs e)
{
if (e.Info == SqlNotificationInfo.Invalid)
{
Console.WriteLine("The above notification query is not valid.");
}
else
{
Console.WriteLine("Database Changed based on query");
Console.WriteLine("------------------------------------");
Console.WriteLine("Event Details:");
Console.WriteLine("Notification Info: " + e.Info);
Console.WriteLine("Notification source: " + e.Source);
Console.WriteLine("Notification type: " + e.Type);
}
//PushMessage logic here
bool isPushMessageSend = false;
string postString = "";
string urlpath = "https://api.parse.com/1/push";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlpath);
// Use Query to get device_id?
postString = "{\"data\": { \"alert\": \"Finally is working\" },\"where\": { \"device_id\": \"" + "deviceID" + "\" }}";
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = postString.Length;
httpWebRequest.Headers.Add("X-Parse-Application-Id", "XXXX");
httpWebRequest.Headers.Add("X-Parse-REST-API-KEY", "XXXX");
httpWebRequest.Method = "POST";
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
JObject jObjRes = JObject.Parse(responseText);
if (Convert.ToString(jObjRes).IndexOf("true") != -1)
{
isPushMessageSend = true;
}
}
// Resume Monitoring... Requires setting up a new connection, etc.. Reuse existing connection? Tried.
MonitorDatabase();
}
}
}
class Program
{
static void Main(string[] args)
{
try
{
// Start the cheese monitor
DbMonitor dbMonitor = new DbMonitor();
dbMonitor.MonitorDatabase();
Console.WriteLine("Monitoring....Press any key to stop.");
Console.Read();
dbMonitor.Stop();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
finally
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["XXXXX"].ConnectionString);
}
}
}